4 \section[Coverage]{@coverage@: the main function}
7 module Coverage (addCoverageTicksToBinds) where
9 #include "HsVersions.h"
13 import DynFlags ( DynFlags, mainModIs, mainFunIs )
15 import HscTypes ( HpcInfo, noHpcInfo )
19 import DynFlags ( DynFlag(Opt_D_dump_hpc), hpcDir )
23 import ErrUtils (doIfSet_dyn)
24 import HsUtils ( mkHsApp )
34 import TysWiredIn ( intTy , stringTy, unitTy, intDataCon, falseDataConId, mkListTy, pairTyCon, tupleCon, mkTupleTy, unboxedSingletonDataCon )
36 import Var ( TyVar, mkTyVar )
37 import DataCon ( dataConWrapId )
40 import BasicTypes ( RecFlag(..), Activation(NeverActive), Boxity(..) )
41 import Data.List ( isSuffixOf )
43 import System.Time (ClockTime(..))
44 import System.Directory (getModificationTime)
45 import System.IO (FilePath)
46 #if __GLASGOW_HASKELL__ < 603
47 import Compat.Directory ( createDirectoryIfMissing )
49 import System.Directory ( createDirectoryIfMissing )
53 %************************************************************************
55 %* The main function: addCoverageTicksToBinds
57 %************************************************************************
60 addCoverageTicksToBinds dflags mod mod_loc binds = do
62 case ml_hs_file mod_loc of
64 Nothing -> error "can not find the original file during hpc trans"
66 ; if "boot" `isSuffixOf` orig_file then return (binds, 0)
67 else addCoverageTicksToBinds2 dflags mod orig_file binds
70 addCoverageTicksToBinds2 dflags mod orig_file binds = do
71 let main_mod = mainModIs dflags
72 main_is = case mainFunIs dflags of
76 modTime <- getModificationTime' orig_file
78 let mod_name = moduleNameString (moduleName mod)
81 = unTM (addTickLHsBinds binds)
82 $ TT { modName = mod_name
88 let hpc_dir = hpcDir dflags
90 -- write the mix entries for this module
91 let tabStop = 1 -- <tab> counts as a normal char in GHC's location ranges.
93 createDirectoryIfMissing True hpc_dir
95 mixCreate hpc_dir mod_name (Mix orig_file modTime tabStop $ reverse $ mixEntries st)
97 doIfSet_dyn dflags Opt_D_dump_hpc $ do
98 printDump (pprLHsBinds binds1)
99 -- putStrLn (showSDocDebug (pprLHsBinds binds3))
100 return (binds1, tickBoxCount st)
105 liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a)
106 liftL f (L loc a) = do
110 addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id)
111 addTickLHsBinds binds = mapBagM addTickLHsBind binds
113 addTickLHsBind :: LHsBind Id -> TM (LHsBind Id)
114 addTickLHsBind (L pos (AbsBinds abs_tvs abs_dicts abs_exports abs_binds)) = do
115 abs_binds' <- addTickLHsBinds abs_binds
116 return $ L pos $ AbsBinds abs_tvs abs_dicts abs_exports abs_binds'
117 addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do
118 let name = getOccString id
119 decl_path <- getPathEntry
121 tick_no <- allocATickBox (if null decl_path
122 then TopLevelBox [name]
123 else LocalBox (name : decl_path))
126 mg@(MatchGroup matches' ty) <- addPathEntry (getOccString id)
127 $ addTickMatchGroup (fun_matches funBind)
128 let arg_count = matchGroupArity mg
129 let (tys,res_ty) = splitFunTysN arg_count ty
131 return $ L pos $ funBind { fun_matches = MatchGroup matches' ty
135 -- TODO: Revisit this
136 addTickLHsBind (L pos (pat@(PatBind { pat_rhs = rhs }))) = do
138 rhs' <- addPathEntry name $ addTickGRHSs False rhs
140 decl_path <- getPathEntry
141 tick_me <- allocTickBox (if null decl_path
142 then TopLevelBox [name]
143 else LocalBox (name : decl_path))
145 return $ L pos $ pat { pat_rhs = rhs' }
147 {- only internal stuff, not from source, uses VarBind, so we ignore it.
148 addTickLHsBind (VarBind var_id var_rhs) = do
149 var_rhs' <- addTickLHsExpr var_rhs
150 return $ VarBind var_id var_rhs'
152 addTickLHsBind other = return other
154 addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id)
155 addTickLHsExpr (L pos e0) = do
156 e1 <- addTickHsExpr e0
157 fn <- allocTickBox ExpBox pos
158 return $ fn $ L pos e1
160 addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id)
161 addTickLHsExprOptAlt oneOfMany (L pos e0) = do
162 e1 <- addTickHsExpr e0
163 fn <- allocTickBox (if oneOfMany then AltBox else ExpBox) pos
164 return $ fn $ L pos e1
166 -- version of addTick that does not actually add a tick,
167 -- because the scope of this tick is completely subsumed by
169 addTickLHsExpr' :: LHsExpr Id -> TM (LHsExpr Id)
170 addTickLHsExpr' (L pos e0) = do
171 e1 <- addTickHsExpr e0
174 addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id)
175 addBinTickLHsExpr boxLabel (L pos e0) = do
176 e1 <- addTickHsExpr e0
177 allocBinTickBox boxLabel $ L pos e1
180 addTickHsExpr :: HsExpr Id -> TM (HsExpr Id)
181 addTickHsExpr e@(HsVar _) = return e
182 addTickHsExpr e@(HsIPVar _) = return e
183 addTickHsExpr e@(HsOverLit _) = return e
184 addTickHsExpr e@(HsLit _) = return e
185 addTickHsExpr e@(HsLam matchgroup) =
186 liftM HsLam (addTickMatchGroup matchgroup)
187 addTickHsExpr (HsApp e1 e2) =
188 liftM2 HsApp (addTickLHsExpr' e1) (addTickLHsExpr e2)
189 addTickHsExpr (OpApp e1 e2 fix e3) =
195 addTickHsExpr ( NegApp e neg) =
198 (addTickSyntaxExpr hpcSrcSpan neg)
199 addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExpr' e)
200 addTickHsExpr (SectionL e1 e2) =
204 addTickHsExpr (SectionR e1 e2) =
208 addTickHsExpr (HsCase e mgs) =
211 (addTickMatchGroup mgs)
212 addTickHsExpr (HsIf e1 e2 e3) =
214 (addBinTickLHsExpr CondBinBox e1)
215 (addTickLHsExprOptAlt True e2)
216 (addTickLHsExprOptAlt True e3)
217 addTickHsExpr (HsLet binds e) =
219 (addTickHsLocalBinds binds) -- to think about: !patterns.
221 addTickHsExpr (HsDo cxt stmts last_exp srcloc) =
224 (mapM (liftL (addTickStmt forQual)) stmts)
225 (addTickLHsExpr last_exp)
228 forQual = case cxt of
229 ListComp -> Just QualBinBox
231 addTickHsExpr (ExplicitList ty es) =
234 (mapM addTickLHsExpr es)
235 addTickHsExpr (ExplicitPArr {}) = error "addTickHsExpr: ExplicitPArr "
236 addTickHsExpr (ExplicitTuple es box) =
238 (mapM addTickLHsExpr es)
240 addTickHsExpr (RecordCon id ty rec_binds) =
244 (addTickHsRecordBinds rec_binds)
245 addTickHsExpr (RecordUpd e rec_binds ty1 ty2) =
248 (addTickHsRecordBinds rec_binds)
251 addTickHsExpr (ExprWithTySig {}) = error "addTickHsExpr: ExprWithTySig"
252 addTickHsExpr (ExprWithTySigOut e ty) =
253 liftM2 ExprWithTySigOut
254 (addTickLHsExpr' e) -- No need to tick the inner expression
255 -- for expressions with signatures
257 addTickHsExpr (ArithSeq ty arith_seq) =
260 (addTickArithSeqInfo arith_seq)
261 addTickHsExpr (PArrSeq {}) = error "addTickHsExpr: PArrSeq "
262 addTickHsExpr (HsSCC {}) = error "addTickHsExpr: HsSCC "
263 addTickHsExpr (HsCoreAnn {}) = error "addTickHsExpr: HsCoreAnn "
264 addTickHsExpr e@(HsBracket {}) = return e
265 addTickHsExpr e@(HsBracketOut {}) = return e
266 addTickHsExpr e@(HsSpliceE {}) = return e
267 addTickHsExpr (HsProc pat cmdtop) =
270 (liftL addTickHsCmdTop cmdtop)
271 addTickHsExpr (HsWrap w e) =
274 (addTickHsExpr e) -- explicitly no tick on inside
275 addTickHsExpr (HsArrApp e1 e2 ty1 arr_ty lr) =
282 addTickHsExpr (HsArrForm e fix cmdtop) =
286 (mapM (liftL addTickHsCmdTop) cmdtop)
288 addTickHsExpr e@(HsType ty) = return e
290 -- Should never happen in expression content.
291 addTickHsExpr (EAsPat _ _) = error "addTickHsExpr: EAsPat _ _"
292 addTickHsExpr (ELazyPat _) = error "addTickHsExpr: ELazyPat _"
293 addTickHsExpr (EWildPat) = error "addTickHsExpr: EWildPat"
294 addTickHsExpr (HsBinTick _ _ _) = error "addTickhsExpr: HsBinTick _ _ _"
295 addTickHsExpr (HsTick _ _) = error "addTickhsExpr: HsTick _ _"
297 addTickMatchGroup (MatchGroup matches ty) = do
298 let isOneOfMany = matchesOneOfMany matches
299 matches' <- mapM (liftL (addTickMatch isOneOfMany)) matches
300 return $ MatchGroup matches' ty
302 addTickMatch :: Bool -> Match Id -> TM (Match Id)
303 addTickMatch isOneOfMany (Match pats opSig gRHSs) = do
304 gRHSs' <- addTickGRHSs isOneOfMany gRHSs
305 return $ Match pats opSig gRHSs'
307 addTickGRHSs :: Bool -> GRHSs Id -> TM (GRHSs Id)
308 addTickGRHSs isOneOfMany (GRHSs guarded local_binds) = do
309 guarded' <- mapM (liftL (addTickGRHS isOneOfMany)) guarded
310 local_binds' <- addTickHsLocalBinds local_binds
311 return $ GRHSs guarded' local_binds'
313 addTickGRHS :: Bool -> GRHS Id -> TM (GRHS Id)
314 addTickGRHS isOneOfMany (GRHS stmts expr) = do
315 stmts' <- mapM (liftL (addTickStmt (Just $ GuardBinBox))) stmts
316 expr' <- addTickLHsExprOptAlt isOneOfMany expr
317 return $ GRHS stmts' expr'
320 addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id -> TM (Stmt Id)
321 addTickStmt isGuard (BindStmt pat e bind fail) =
325 (addTickSyntaxExpr hpcSrcSpan bind)
326 (addTickSyntaxExpr hpcSrcSpan fail)
327 addTickStmt isGuard (ExprStmt e bind' ty) =
330 (addTickSyntaxExpr hpcSrcSpan bind')
333 addTick e | Just fn <- isGuard = addBinTickLHsExpr fn e
334 | otherwise = addTickLHsExpr e
336 addTickStmt isGuard (LetStmt binds) =
338 (addTickHsLocalBinds binds)
339 addTickStmt isGuard (ParStmt pairs) =
340 liftM ParStmt (mapM process pairs)
342 process (stmts,ids) =
344 (mapM (liftL (addTickStmt isGuard)) stmts)
346 addTickStmt isGuard (RecStmt stmts ids1 ids2 tys dictbinds) =
348 (mapM (liftL (addTickStmt isGuard)) stmts)
352 (addTickDictBinds dictbinds)
354 addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id)
355 addTickHsLocalBinds (HsValBinds binds) =
357 (addTickHsValBinds binds)
358 addTickHsLocalBinds (HsIPBinds binds) =
360 (addTickHsIPBinds binds)
361 addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds
363 addTickHsValBinds (ValBindsOut binds sigs) =
365 (mapM (\ (rec,binds') ->
368 (addTickLHsBinds binds'))
372 addTickHsIPBinds (IPBinds ipbinds dictbinds) =
374 (mapM (liftL addTickIPBind) ipbinds)
375 (addTickDictBinds dictbinds)
377 addTickIPBind :: IPBind Id -> TM (IPBind Id)
378 addTickIPBind (IPBind nm e) =
383 -- There is no location here, so we might need to use a context location??
384 addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id)
385 addTickSyntaxExpr pos x = do
386 L _ x' <- addTickLHsExpr (L pos x)
388 -- we do not walk into patterns.
389 addTickLPat :: LPat Id -> TM (LPat Id)
390 addTickLPat pat = return pat
392 addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id)
393 addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) =
400 addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id)
401 addTickLHsCmd x = addTickLHsExpr x
403 addTickDictBinds :: DictBinds Id -> TM (DictBinds Id)
404 addTickDictBinds x = addTickLHsBinds x
406 addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id)
407 addTickHsRecordBinds pairs = mapM process pairs
412 (addTickLHsExpr expr)
414 addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id)
415 addTickArithSeqInfo (From e1) =
418 addTickArithSeqInfo (FromThen e1 e2) =
422 addTickArithSeqInfo (FromTo e1 e2) =
426 addTickArithSeqInfo (FromThenTo e1 e2 e3) =
434 data TixFlags = TixFlags
436 data TickTransState = TT { modName :: String
437 , declPath :: [String]
439 , mixEntries :: [MixEntry]
443 data TM a = TM { unTM :: TickTransState -> (a,TickTransState) }
445 instance Monad TM where
446 return a = TM $ \ st -> (a,st)
447 (TM m) >>= k = TM $ \ st -> case m st of
448 (r1,st1) -> unTM (k r1) st1
450 --addTick :: LHsExpr Id -> TM (LHsExpr Id)
451 --addTick e = TM $ \ uq -> (e,succ uq,[(uq,getLoc e)])
453 addPathEntry :: String -> TM a -> TM a
454 addPathEntry nm (TM m) = TM $ \ st -> case m (st { declPath = declPath st ++ [nm] }) of
455 (r,st') -> (r,st' { declPath = declPath st })
457 getPathEntry :: TM [String]
458 getPathEntry = TM $ \ st -> (declPath st,st)
460 -- the tick application inherits the source position of its
461 -- expression argument to support nested box allocations
462 allocTickBox :: BoxLabel -> SrcSpan -> TM (LHsExpr Id -> LHsExpr Id)
463 allocTickBox boxLabel pos | Just hpcPos <- mkHpcPos pos = TM $ \ st ->
464 let me = (hpcPos,boxLabel)
467 in ( \ (L pos e) -> L pos $ HsTick c (L pos e)
468 , st {tickBoxCount=c+1,mixEntries=me:mes}
470 allocTickBox boxLabel e = return id
472 -- the tick application inherits the source position of its
473 -- expression argument to support nested box allocations
474 allocATickBox :: BoxLabel -> SrcSpan -> TM (Maybe Int)
475 allocATickBox boxLabel pos | Just hpcPos <- mkHpcPos pos = TM $ \ st ->
476 let me = (hpcPos,boxLabel)
480 , st {tickBoxCount=c+1,mixEntries=me:mes}
482 allocATickBox boxLabel e = return Nothing
484 allocBinTickBox :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id)
485 allocBinTickBox boxLabel (L pos e) | Just hpcPos <- mkHpcPos pos = TM $ \ st ->
486 let meT = (hpcPos,boxLabel True)
487 meF = (hpcPos,boxLabel False)
488 meE = (hpcPos,ExpBox)
491 in ( L pos $ HsTick c $ L pos $ HsBinTick (c+1) (c+2) (L pos e)
492 -- notice that F and T are reversed,
493 -- because we are building the list in
495 , st {tickBoxCount=c+3,mixEntries=meF:meT:meE:mes}
498 allocBinTickBox boxLabel e = return e
500 mkHpcPos :: SrcSpan -> Maybe HpcPos
502 | not (isGoodSrcSpan pos) = Nothing
503 | start == end = Nothing -- no actual location
504 | otherwise = Just hpcPos
506 start = srcSpanStart pos
508 hpcPos = toHpcPos ( srcLocLine start
509 , srcLocCol start + 1
514 hpcSrcSpan = mkGeneralSrcSpan (FSLIT("Haskell Program Coverage internals"))
516 -- all newly allocated locations have an HPC tag on them, to help debuging
517 hpcLoc :: e -> Located e
518 hpcLoc = L hpcSrcSpan
523 matchesOneOfMany :: [LMatch Id] -> Bool
524 matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1
526 matchCount (L _ (Match _pats _ty (GRHSs grhss _binds))) = length grhss
531 ---------------------------------------------------------------
532 -- Datatypes and file-access routines for the per-module (.mix)
533 -- indexes used by Hpc.
534 -- Colin Runciman and Andy Gill, June 2006
535 ---------------------------------------------------------------
537 -- a module index records the attributes of each tick-box that has
538 -- been introduced in that module, accessed by tick-number position
542 FilePath -- location of original file
543 Integer -- time (in seconds) of original file's last update, since 1970.
544 Int -- tab stop value
545 [MixEntry] -- entries
548 -- We would rather use ClockTime in Mix, but ClockTime has no Read instance in 6.4 and before,
549 -- but does in 6.6. Definining the instance for ClockTime here is the Wrong Thing to do,
550 -- because if some other program also defined that instance, we will not be able to compile.
552 type MixEntry = (HpcPos, BoxLabel)
554 data BoxLabel = ExpBox
556 | TopLevelBox [String]
558 -- | UserBox (Maybe String)
562 -- | PreludeBinBox String Bool
563 -- | UserBinBox (Maybe String) Bool
564 deriving (Read, Show)
566 mixCreate :: String -> String -> Mix -> IO ()
567 mixCreate dirName modName mix =
568 writeFile (mixName dirName modName) (show mix)
570 readMix :: FilePath -> String -> IO Mix
571 readMix dirName modName = do
572 contents <- readFile (mixName dirName modName)
573 return (read contents)
575 mixName :: FilePath -> String -> String
576 mixName dirName name = dirName ++ "/" ++ name ++ ".mix"
578 getModificationTime' :: FilePath -> IO Integer
579 getModificationTime' file = do
580 (TOD sec _) <- System.Directory.getModificationTime file
583 data Tix = Tix [PixEntry] -- The number of tickboxes in each module
584 [TixEntry] -- The tick boxes
585 deriving (Read, Show,Eq)
587 type TixEntry = Integer
589 -- always read and write Tix from the current working directory.
591 readTix :: String -> IO (Maybe Tix)
593 catch (do contents <- readFile $ tixName pname
594 return $ Just $ read contents)
595 (\ _ -> return $ Nothing)
597 writeTix :: String -> Tix -> IO ()
599 writeFile (tixName pname) (show tix)
601 tixName :: String -> String
602 tixName name = name ++ ".tix"
604 -- a program index records module names and numbers of tick-boxes
605 -- introduced in each module that has been transformed for coverage
607 data Pix = Pix [PixEntry] deriving (Read, Show)
609 type PixEntry = ( String -- module name
610 , Int -- number of boxes
613 pixUpdate :: FilePath -> String -> String -> Int -> IO ()
614 pixUpdate dirName progName modName boxCount = do
615 fileUpdate (pixName dirName progName) pixAssign (Pix [])
617 pixAssign :: Pix -> Pix
618 pixAssign (Pix pes) =
619 Pix ((modName,boxCount) : filter ((/=) modName . fst) pes)
621 readPix :: FilePath -> String -> IO Pix
622 readPix dirName pname = do
623 contents <- readFile (pixName dirName pname)
624 return (read contents)
626 tickCount :: Pix -> Int
627 tickCount (Pix mp) = sum $ map snd mp
629 pixName :: FilePath -> String -> String
630 pixName dirName name = dirName ++ "/" ++ name ++ ".pix"
632 -- updating a value stored in a file via read and show
633 fileUpdate :: (Read a, Show a) => String -> (a->a) -> a -> IO()
634 fileUpdate fname update init =
637 valueText <- readFile fname
638 ( case finite valueText of
640 writeFile fname (show (update (read valueText))) ))
641 (const (writeFile fname (show (update init))))
643 finite :: [a] -> Bool
645 finite (x:xs) = finite xs
647 data HpcPos = P !Int !Int !Int !Int deriving (Eq)
649 fromHpcPos :: HpcPos -> (Int,Int,Int,Int)
650 fromHpcPos (P l1 c1 l2 c2) = (l1,c1,l2,c2)
652 toHpcPos :: (Int,Int,Int,Int) -> HpcPos
653 toHpcPos (l1,c1,l2,c2) = P l1 c1 l2 c2
655 instance Show HpcPos where
656 show (P l1 c1 l2 c2) = show l1 ++ ':' : show c1 ++ '-' : show l2 ++ ':' : show c2
658 instance Read HpcPos where
659 readsPrec _i pos = [(toHpcPos (read l1,read c1,read l2,read c2),after)]
661 (before,after) = span (/= ',') pos
662 (lhs,rhs) = case span (/= '-') before of
663 (lhs,'-':rhs) -> (lhs,rhs)
664 (lhs,"") -> (lhs,lhs)
665 (l1,':':c1) = span (/= ':') lhs
666 (l2,':':c2) = span (/= ':') rhs