2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[CoreMonad]{The core pipeline monad}
7 {-# LANGUAGE UndecidableInstances #-}
13 -- ** Reading from the monad
14 getHscEnv, getAnnEnv, getRuleBase, getModule,
15 getDynFlags, getOrigNameCache,
17 -- ** Writing to the monad
20 -- ** Lifting into the monad
21 liftIO, liftIOWithCount,
22 liftIO1, liftIO2, liftIO3, liftIO4,
24 -- ** Dealing with annotations
25 findAnnotations, deserializeAnnotations, addAnnotation,
31 putMsg, putMsgS, errorMsg, errorMsgS,
32 fatalErrorMsg, fatalErrorMsgS,
33 debugTraceMsg, debugTraceMsgS,
48 import CoreLint ( lintCoreBindings )
49 import PrelNames ( iNTERACTIVE )
51 import Module ( Module )
52 import DynFlags ( DynFlags, DynFlag )
53 import SimplMonad ( SimplCount, plusSimplCount, zeroSimplCount )
54 import Rules ( RuleBase )
58 import IOEnv hiding ( liftIO, failM, failWithM )
59 import qualified IOEnv ( liftIO )
60 import TcEnv ( tcLookupGlobal )
61 import TcRnMonad ( TcM, initTc )
65 import qualified ErrUtils as Err
68 import LazyUniqFM ( UniqFM )
75 import Prelude hiding ( read )
78 import {-# SOURCE #-} TcSplice ( lookupThName_maybe )
79 import qualified Language.Haskell.TH as TH
83 %************************************************************************
87 %************************************************************************
89 These functions are not CoreM monad stuff, but they probably ought to
90 be, and it makes a conveneint place. place for them. They print out
91 stuff before and after core passes, and do Core Lint when necessary.
94 endPass :: DynFlags -> String -> DynFlag -> [CoreBind] -> [CoreRule] -> IO ()
95 endPass = dumpAndLint Err.dumpIfSet_core
97 endPassIf :: Bool -> DynFlags -> String -> DynFlag -> [CoreBind] -> [CoreRule] -> IO ()
98 endPassIf cond = dumpAndLint (Err.dumpIf_core cond)
100 dumpAndLint :: (DynFlags -> DynFlag -> String -> SDoc -> IO ())
101 -> DynFlags -> String -> DynFlag
102 -> [CoreBind] -> [CoreRule] -> IO ()
103 dumpAndLint dump dflags pass_name dump_flag binds rules
104 = do { -- Report result size if required
105 -- This has the side effect of forcing the intermediate to be evaluated
106 ; Err.debugTraceMsg dflags 2 $
107 (text " Result size =" <+> int (coreBindsSize binds))
109 -- Report verbosely, if required
110 ; dump dflags dump_flag pass_name
111 (pprCoreBindings binds $$ ppUnless (null rules) pp_rules)
114 ; lintCoreBindings dflags pass_name binds }
116 pp_rules = vcat [ blankLine
117 , ptext (sLit "------ Local rules for imported ids --------")
122 %************************************************************************
124 Monad and carried data structure definitions
126 %************************************************************************
129 data CoreState = CoreState {
130 cs_uniq_supply :: UniqSupply,
134 data CoreReader = CoreReader {
135 cr_hsc_env :: HscEnv,
136 cr_rule_base :: RuleBase,
140 data CoreWriter = CoreWriter {
141 cw_simpl_count :: SimplCount
144 emptyWriter :: DynFlags -> CoreWriter
145 emptyWriter dflags = CoreWriter {
146 cw_simpl_count = zeroSimplCount dflags
149 plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
150 plusWriter w1 w2 = CoreWriter {
151 cw_simpl_count = (cw_simpl_count w1) `plusSimplCount` (cw_simpl_count w2)
154 type CoreIOEnv = IOEnv CoreReader
156 -- | The monad used by Core-to-Core passes to access common state, register simplification
157 -- statistics and so on
158 newtype CoreM a = CoreM { unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }
160 instance Functor CoreM where
165 instance Monad CoreM where
166 return x = CoreM (\s -> nop s x)
167 mx >>= f = CoreM $ \s -> do
168 (x, s', w1) <- unCoreM mx s
169 (y, s'', w2) <- unCoreM (f x) s'
170 return (y, s'', w1 `plusWriter` w2)
172 instance Applicative CoreM where
176 -- For use if the user has imported Control.Monad.Error from MTL
177 -- Requires UndecidableInstances
178 instance MonadPlus IO => MonadPlus CoreM where
179 mzero = CoreM (const mzero)
180 m `mplus` n = CoreM (\rs -> unCoreM m rs `mplus` unCoreM n rs)
182 instance MonadUnique CoreM where
183 getUniqueSupplyM = do
184 us <- getS cs_uniq_supply
185 let (us1, us2) = splitUniqSupply us
186 modifyS (\s -> s { cs_uniq_supply = us2 })
195 -> IO (a, SimplCount)
196 runCoreM hsc_env ann_env rule_base us mod m =
197 liftM extract $ runIOEnv reader $ unCoreM m state
199 reader = CoreReader {
200 cr_hsc_env = hsc_env,
201 cr_rule_base = rule_base,
209 extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
210 extract (value, _, writer) = (value, cw_simpl_count writer)
215 %************************************************************************
217 Core combinators, not exported
219 %************************************************************************
223 nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
226 return (x, s, emptyWriter $ (hsc_dflags . cr_hsc_env) r)
228 read :: (CoreReader -> a) -> CoreM a
229 read f = CoreM (\s -> getEnv >>= (\r -> nop s (f r)))
231 getS :: (CoreState -> a) -> CoreM a
232 getS f = CoreM (\s -> nop s (f s))
234 modifyS :: (CoreState -> CoreState) -> CoreM ()
235 modifyS f = CoreM (\s -> nop (f s) ())
237 write :: CoreWriter -> CoreM ()
238 write w = CoreM (\s -> return ((), s, w))
242 \subsection{Lifting IO into the monad}
246 -- | Lift an 'IOEnv' operation into 'CoreM'
247 liftIOEnv :: CoreIOEnv a -> CoreM a
248 liftIOEnv mx = CoreM (\s -> mx >>= (\x -> nop s x))
250 instance MonadIO CoreM where
251 liftIO = liftIOEnv . IOEnv.liftIO
253 -- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
254 liftIOWithCount :: IO (SimplCount, a) -> CoreM a
255 liftIOWithCount what = liftIO what >>= (\(count, x) -> addSimplCount count >> return x)
260 %************************************************************************
262 Reader, writer and state accessors
264 %************************************************************************
268 getHscEnv :: CoreM HscEnv
269 getHscEnv = read cr_hsc_env
271 getAnnEnv :: CoreM AnnEnv
272 getAnnEnv = getS cs_ann_env
274 getRuleBase :: CoreM RuleBase
275 getRuleBase = read cr_rule_base
277 getModule :: CoreM Module
278 getModule = read cr_module
280 addSimplCount :: SimplCount -> CoreM ()
281 addSimplCount count = write (CoreWriter { cw_simpl_count = count })
283 -- Convenience accessors for useful fields of HscEnv
285 getDynFlags :: CoreM DynFlags
286 getDynFlags = fmap hsc_dflags getHscEnv
288 -- | The original name cache is the current mapping from 'Module' and
289 -- 'OccName' to a compiler-wide unique 'Name'
290 getOrigNameCache :: CoreM OrigNameCache
291 getOrigNameCache = do
292 nameCacheRef <- fmap hsc_NC getHscEnv
293 liftIO $ fmap nsNames $ readIORef nameCacheRef
298 %************************************************************************
300 Dealing with annotations
302 %************************************************************************
306 -- | Find all the annotations we currently know about for the given target. Note that no
307 -- annotations will be returned if we haven't loaded information about the particular target
308 -- you are inquiring about: by default, only those modules that have been imported by the
309 -- program being compiled will have been loaded in this way.
311 -- To load the information from additional modules, you can use the functions 'DynamicLoading.forceLoadModuleInterfaces'
312 -- and 'DynamicLoading.forceLoadNameModuleInterface', but be aware that doing this indiscriminantly
313 -- will impose a performance penalty.
315 -- If no deserialization function is supplied, only transient annotations will be returned.
316 findAnnotations :: Typeable a => ([Word8] -> a) -> CoreAnnTarget -> CoreM [a]
317 findAnnotations deserialize target = do
319 return (findAnns deserialize ann_env target)
321 -- | Deserialize all annotations of a given type. This happens lazily, that is
322 -- no deserialization will take place until the [a] is actually demanded and
323 -- the [a] can also be empty (the UniqFM is not filtered).
324 deserializeAnnotations :: Typeable a => ([Word8] -> a) -> CoreM (UniqFM [a])
325 deserializeAnnotations deserialize = do
327 return (deserializeAnns deserialize ann_env)
329 addAnnotation :: Typeable a => (a -> [Word8]) -> CoreAnnTarget -> a -> CoreM ()
330 addAnnotation serialize target what = addAnnotationToEnv $ Annotation { ann_target = target, ann_value = toSerialized serialize what }
332 addAnnotationToEnv :: Annotation -> CoreM ()
333 addAnnotationToEnv annotation = modifyS (\state -> state { cs_ann_env = extendAnnEnvList (cs_ann_env state) [annotation] })
338 %************************************************************************
342 %************************************************************************
346 msg :: (DynFlags -> SDoc -> IO ()) -> SDoc -> CoreM ()
348 dflags <- getDynFlags
349 liftIO $ how dflags doc
351 -- | Output a String message to the screen
352 putMsgS :: String -> CoreM ()
353 putMsgS = putMsg . text
355 -- | Output a message to the screen
356 putMsg :: SDoc -> CoreM ()
357 putMsg = msg Err.putMsg
359 -- | Output a string error to the screen
360 errorMsgS :: String -> CoreM ()
361 errorMsgS = errorMsg . text
363 -- | Output an error to the screen
364 errorMsg :: SDoc -> CoreM ()
365 errorMsg = msg Err.errorMsg
367 -- | Output a fatal string error to the screen. Note this does not by itself cause the compiler to die
368 fatalErrorMsgS :: String -> CoreM ()
369 fatalErrorMsgS = fatalErrorMsg . text
371 -- | Output a fatal error to the screen. Note this does not by itself cause the compiler to die
372 fatalErrorMsg :: SDoc -> CoreM ()
373 fatalErrorMsg = msg Err.fatalErrorMsg
375 -- | Output a string debugging message at verbosity level of @-v@ or higher
376 debugTraceMsgS :: String -> CoreM ()
377 debugTraceMsgS = debugTraceMsg . text
379 -- | Outputs a debugging message at verbosity level of @-v@ or higher
380 debugTraceMsg :: SDoc -> CoreM ()
381 debugTraceMsg = msg (flip Err.debugTraceMsg 3)
383 -- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
384 dumpIfSet_dyn :: DynFlag -> String -> SDoc -> CoreM ()
385 dumpIfSet_dyn flag str = msg (\dflags -> Err.dumpIfSet_dyn dflags flag str)
390 initTcForLookup :: HscEnv -> TcM a -> IO a
391 initTcForLookup hsc_env = liftM (expectJust "initTcInteractive" . snd) . initTc hsc_env HsSrcFile False iNTERACTIVE
396 %************************************************************************
400 %************************************************************************
403 instance MonadThings CoreM where
404 lookupThing name = do
406 liftIO $ initTcForLookup hsc_env (tcLookupGlobal name)
409 %************************************************************************
411 Template Haskell interoperability
413 %************************************************************************
417 -- | Attempt to convert a Template Haskell name to one that GHC can
418 -- understand. Original TH names such as those you get when you use
419 -- the @'foo@ syntax will be translated to their equivalent GHC name
420 -- exactly. Qualified or unqualifed TH names will be dynamically bound
421 -- to names in the module being compiled, if possible. Exact TH names
422 -- will be bound to the name they represent, exactly.
423 thNameToGhcName :: TH.Name -> CoreM (Maybe Name)
424 thNameToGhcName th_name = do
426 liftIO $ initTcForLookup hsc_env (lookupThName_maybe th_name)