3 % (c) University of Glasgow, 2007
5 \section[Coverage]{@coverage@: the main function}
8 module Coverage (addCoverageTicksToBinds) where
10 #include "HsVersions.h"
27 import System.Time (ClockTime(..))
28 import System.Directory (getModificationTime)
29 import System.IO (FilePath)
30 #if __GLASGOW_HASKELL__ < 603
31 import Compat.Directory ( createDirectoryIfMissing )
33 import System.Directory ( createDirectoryIfMissing )
40 %************************************************************************
42 %* The main function: addCoverageTicksToBinds
44 %************************************************************************
47 addCoverageTicksToBinds
50 -> ModLocation -- of the current module
52 -> IO (LHsBinds Id, Int, ModBreaks)
54 addCoverageTicksToBinds dflags mod mod_loc binds = do
56 case ml_hs_file mod_loc of
58 Nothing -> panic "can not find the original file during hpc trans"
60 if "boot" `isSuffixOf` orig_file then return (binds, 0, emptyModBreaks) else do
62 let mod_name = moduleNameString (moduleName mod)
65 = unTM (addTickLHsBinds binds)
66 $ TT { modName = mod_name
72 let entries = reverse $ mixEntries st
74 -- write the mix entries for this module
76 let hpc_dir = hpcDir dflags
77 let tabStop = 1 -- <tab> counts as a normal char in GHC's location ranges.
78 createDirectoryIfMissing True hpc_dir
79 modTime <- getModificationTime' orig_file
80 mixCreate hpc_dir mod_name (Mix orig_file modTime tabStop entries)
82 -- Todo: use proper src span type
83 breakArray <- newBreakArray $ length entries
84 let fn = mkFastString orig_file
85 let locsTicks = listArray (0,tickBoxCount st-1)
86 [ mkSrcSpan (mkSrcLoc fn r1 c1) (mkSrcLoc fn r2 c2)
87 | (P r1 c1 r2 c2, _box) <- entries ]
89 let modBreaks = emptyModBreaks
90 { modBreaks_flags = breakArray
91 , modBreaks_locs = locsTicks
94 doIfSet_dyn dflags Opt_D_dump_hpc $ do
95 printDump (pprLHsBinds binds1)
97 return (binds1, tickBoxCount st, modBreaks)
102 liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a)
103 liftL f (L loc a) = do
107 addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id)
108 addTickLHsBinds binds = mapBagM addTickLHsBind binds
110 addTickLHsBind :: LHsBind Id -> TM (LHsBind Id)
111 addTickLHsBind (L pos (AbsBinds abs_tvs abs_dicts abs_exports abs_binds)) = do
112 abs_binds' <- addTickLHsBinds abs_binds
113 return $ L pos $ AbsBinds abs_tvs abs_dicts abs_exports abs_binds'
115 addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do
116 let name = getOccString id
117 decl_path <- getPathEntry
119 mg@(MatchGroup matches' ty) <- addPathEntry name
120 $ addTickMatchGroup (fun_matches funBind)
122 -- Todo: we don't want redundant ticks on simple pattern bindings
123 if not opt_Hpc && isSimplePatBind funBind
125 return $ L pos $ funBind { fun_matches = MatchGroup matches' ty
129 tick_no <- allocATickBox (if null decl_path
130 then TopLevelBox [name]
131 else LocalBox (name : decl_path)) pos
133 return $ L pos $ funBind { fun_matches = MatchGroup matches' ty
137 -- a binding is a simple pattern binding if it is a funbind with zero patterns
138 isSimplePatBind :: HsBind a -> Bool
139 isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0
141 -- TODO: Revisit this
142 addTickLHsBind (L pos (pat@(PatBind { pat_rhs = rhs }))) = do
144 rhs' <- addPathEntry name $ addTickGRHSs False rhs
146 decl_path <- getPathEntry
147 tick_me <- allocTickBox (if null decl_path
148 then TopLevelBox [name]
149 else LocalBox (name : decl_path))
151 return $ L pos $ pat { pat_rhs = rhs' }
153 {- only internal stuff, not from source, uses VarBind, so we ignore it.
154 addTickLHsBind (VarBind var_id var_rhs) = do
155 var_rhs' <- addTickLHsExpr var_rhs
156 return $ VarBind var_id var_rhs'
158 addTickLHsBind other = return other
160 -- add a tick to the expression no matter what it is
161 addTickLHsExprAlways :: LHsExpr Id -> TM (LHsExpr Id)
162 addTickLHsExprAlways (L pos e0) = do
163 e1 <- addTickHsExpr e0
164 fn <- allocTickBox ExpBox pos
165 return $ fn $ L pos e1
167 -- always a breakpoint tick, maybe an HPC tick
168 addTickLHsExprBreakAlways :: LHsExpr Id -> TM (LHsExpr Id)
169 addTickLHsExprBreakAlways e
170 | opt_Hpc = addTickLHsExpr e
171 | otherwise = addTickLHsExprAlways e
173 -- version of addTick that does not actually add a tick,
174 -- because the scope of this tick is completely subsumed by
176 addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id)
177 addTickLHsExprNever (L pos e0) = do
178 e1 <- addTickHsExpr e0
181 addTickLHsExprBreakOnly :: LHsExpr Id -> TM (LHsExpr Id)
182 addTickLHsExprBreakOnly e
183 | opt_Hpc = addTickLHsExprNever e
184 | otherwise = addTickLHsExprAlways e
186 -- selectively add ticks to interesting expressions
187 addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id)
188 addTickLHsExpr (L pos e0) = do
189 e1 <- addTickHsExpr e0
190 if opt_Hpc || isGoodBreakExpr e0
192 fn <- allocTickBox ExpBox pos
193 return $ fn $ L pos e1
197 -- general heuristic: expressions which do not denote values are good break points
198 isGoodBreakExpr :: HsExpr Id -> Bool
199 isGoodBreakExpr (HsApp {}) = True
200 isGoodBreakExpr (OpApp {}) = True
201 isGoodBreakExpr (NegApp {}) = True
202 isGoodBreakExpr (HsCase {}) = True
203 isGoodBreakExpr (HsIf {}) = True
204 isGoodBreakExpr (RecordCon {}) = True
205 isGoodBreakExpr (RecordUpd {}) = True
206 isGoodBreakExpr (ArithSeq {}) = True
207 isGoodBreakExpr (PArrSeq {}) = True
208 isGoodBreakExpr other = False
210 addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id)
211 addTickLHsExprOptAlt oneOfMany (L pos e0)
212 | not opt_Hpc = addTickLHsExpr (L pos e0)
214 e1 <- addTickHsExpr e0
215 fn <- allocTickBox (if oneOfMany then AltBox else ExpBox) pos
216 return $ fn $ L pos e1
218 addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id)
219 addBinTickLHsExpr boxLabel (L pos e0) = do
220 e1 <- addTickHsExpr e0
221 allocBinTickBox boxLabel $ L pos e1
223 addTickHsExpr :: HsExpr Id -> TM (HsExpr Id)
224 addTickHsExpr e@(HsVar _) = return e
225 addTickHsExpr e@(HsIPVar _) = return e
226 addTickHsExpr e@(HsOverLit _) = return e
227 addTickHsExpr e@(HsLit _) = return e
228 addTickHsExpr e@(HsLam matchgroup) =
229 liftM HsLam (addTickMatchGroup matchgroup)
230 addTickHsExpr (HsApp e1 e2) =
231 liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2)
232 addTickHsExpr (OpApp e1 e2 fix e3) =
235 (addTickLHsExprNever e2)
238 addTickHsExpr (NegApp e neg) =
241 (addTickSyntaxExpr hpcSrcSpan neg)
242 addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprNever e)
243 addTickHsExpr (SectionL e1 e2) =
247 addTickHsExpr (SectionR e1 e2) =
251 addTickHsExpr (HsCase e mgs) =
254 (addTickMatchGroup mgs)
255 addTickHsExpr (HsIf e1 e2 e3) =
257 (addBinTickLHsExpr CondBinBox e1)
258 (addTickLHsExprOptAlt True e2)
259 (addTickLHsExprOptAlt True e3)
260 addTickHsExpr (HsLet binds e) =
262 (addTickHsLocalBinds binds) -- to think about: !patterns.
263 (addTickLHsExprBreakOnly e)
264 addTickHsExpr (HsDo cxt stmts last_exp srcloc) =
267 (mapM (liftL (addTickStmt forQual)) stmts)
268 (addTickLHsExpr last_exp)
271 forQual = case cxt of
272 ListComp -> Just QualBinBox
274 addTickHsExpr (ExplicitList ty es) =
277 (mapM (addTickLHsExpr) es)
278 addTickHsExpr (ExplicitPArr {}) = error "addTickHsExpr: ExplicitPArr"
279 addTickHsExpr (ExplicitTuple es box) =
281 (mapM (addTickLHsExpr) es)
283 addTickHsExpr (RecordCon id ty rec_binds) =
287 (addTickHsRecordBinds rec_binds)
288 addTickHsExpr (RecordUpd e rec_binds ty1 ty2) =
291 (addTickHsRecordBinds rec_binds)
294 addTickHsExpr (ExprWithTySig {}) = error "addTickHsExpr: ExprWithTySig"
295 addTickHsExpr (ExprWithTySigOut e ty) =
296 liftM2 ExprWithTySigOut
297 (addTickLHsExprNever e) -- No need to tick the inner expression
298 -- for expressions with signatures
300 addTickHsExpr (ArithSeq ty arith_seq) =
303 (addTickArithSeqInfo arith_seq)
304 addTickHsExpr (HsTickPragma (file,(l1,c1),(l2,c2)) (L pos e0)) = do
305 e1 <- addTickHsExpr e0
306 fn <- allocTickBox (ExternalBox (unpackFS file) (P l1 c1 l2 c2)) pos
307 let (L _ e2) = fn $ L pos e1
309 addTickHsExpr (PArrSeq {}) = error "addTickHsExpr: PArrSeq"
310 addTickHsExpr (HsSCC {}) = error "addTickHsExpr: HsSCC"
311 addTickHsExpr (HsCoreAnn {}) = error "addTickHsExpr: HsCoreAnn"
312 addTickHsExpr e@(HsBracket {}) = return e
313 addTickHsExpr e@(HsBracketOut {}) = return e
314 addTickHsExpr e@(HsSpliceE {}) = return e
315 addTickHsExpr (HsProc pat cmdtop) =
318 (liftL (addTickHsCmdTop) cmdtop)
319 addTickHsExpr (HsWrap w e) =
322 (addTickHsExpr e) -- explicitly no tick on inside
323 addTickHsExpr (HsArrApp e1 e2 ty1 arr_ty lr) =
330 addTickHsExpr (HsArrForm e fix cmdtop) =
334 (mapM (liftL (addTickHsCmdTop)) cmdtop)
336 addTickHsExpr e@(HsType ty) = return e
338 -- Should never happen in expression content.
339 addTickHsExpr (EAsPat _ _) = error "addTickHsExpr: EAsPat _ _"
340 addTickHsExpr (ELazyPat _) = error "addTickHsExpr: ELazyPat _"
341 addTickHsExpr (EWildPat) = error "addTickHsExpr: EWildPat"
342 addTickHsExpr (HsBinTick _ _ _) = error "addTickhsExpr: HsBinTick _ _ _"
343 addTickHsExpr (HsTick _ _) = error "addTickhsExpr: HsTick _ _"
345 addTickMatchGroup (MatchGroup matches ty) = do
346 let isOneOfMany = matchesOneOfMany matches
347 matches' <- mapM (liftL (addTickMatch isOneOfMany)) matches
348 return $ MatchGroup matches' ty
350 addTickMatch :: Bool -> Match Id -> TM (Match Id)
351 addTickMatch isOneOfMany (Match pats opSig gRHSs) = do
352 gRHSs' <- addTickGRHSs isOneOfMany gRHSs
353 return $ Match pats opSig gRHSs'
355 addTickGRHSs :: Bool -> GRHSs Id -> TM (GRHSs Id)
356 addTickGRHSs isOneOfMany (GRHSs guarded local_binds) = do
357 guarded' <- mapM (liftL (addTickGRHS isOneOfMany)) guarded
358 local_binds' <- addTickHsLocalBinds local_binds
359 return $ GRHSs guarded' local_binds'
361 addTickGRHS :: Bool -> GRHS Id -> TM (GRHS Id)
362 addTickGRHS isOneOfMany (GRHS stmts expr) = do
363 stmts' <- mapM (liftL (addTickStmt (Just $ GuardBinBox))) stmts
364 expr' <- if opt_Hpc then addTickLHsExprOptAlt isOneOfMany expr
365 else addTickLHsExprAlways expr
366 return $ GRHS stmts' expr'
368 addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id -> TM (Stmt Id)
369 addTickStmt isGuard (BindStmt pat e bind fail) =
372 (addTickLHsExprBreakAlways e)
373 (addTickSyntaxExpr hpcSrcSpan bind)
374 (addTickSyntaxExpr hpcSrcSpan fail)
375 addTickStmt isGuard (ExprStmt e bind' ty) =
378 (addTickSyntaxExpr hpcSrcSpan bind')
381 addTick e | Just fn <- isGuard = addBinTickLHsExpr fn e
382 | otherwise = addTickLHsExprBreakAlways e
384 addTickStmt isGuard (LetStmt binds) =
386 (addTickHsLocalBinds binds)
387 addTickStmt isGuard (ParStmt pairs) =
388 liftM ParStmt (mapM process pairs)
390 process (stmts,ids) =
392 (mapM (liftL (addTickStmt isGuard)) stmts)
394 addTickStmt isGuard (RecStmt stmts ids1 ids2 tys dictbinds) =
396 (mapM (liftL (addTickStmt isGuard)) stmts)
400 (addTickDictBinds dictbinds)
402 addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id)
403 addTickHsLocalBinds (HsValBinds binds) =
405 (addTickHsValBinds binds)
406 addTickHsLocalBinds (HsIPBinds binds) =
408 (addTickHsIPBinds binds)
409 addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds
411 addTickHsValBinds (ValBindsOut binds sigs) =
413 (mapM (\ (rec,binds') ->
416 (addTickLHsBinds binds'))
420 addTickHsIPBinds (IPBinds ipbinds dictbinds) =
422 (mapM (liftL (addTickIPBind)) ipbinds)
423 (addTickDictBinds dictbinds)
425 addTickIPBind :: IPBind Id -> TM (IPBind Id)
426 addTickIPBind (IPBind nm e) =
431 -- There is no location here, so we might need to use a context location??
432 addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id)
433 addTickSyntaxExpr pos x = do
434 L _ x' <- addTickLHsExpr (L pos x)
436 -- we do not walk into patterns.
437 addTickLPat :: LPat Id -> TM (LPat Id)
438 addTickLPat pat = return pat
440 addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id)
441 addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) =
448 addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id)
449 addTickLHsCmd x = addTickLHsExpr x
451 addTickDictBinds :: DictBinds Id -> TM (DictBinds Id)
452 addTickDictBinds x = addTickLHsBinds x
454 addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id)
455 addTickHsRecordBinds (HsRecordBinds pairs) = liftM HsRecordBinds (mapM process pairs)
460 (addTickLHsExpr expr)
462 addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id)
463 addTickArithSeqInfo (From e1) =
466 addTickArithSeqInfo (FromThen e1 e2) =
470 addTickArithSeqInfo (FromTo e1 e2) =
474 addTickArithSeqInfo (FromThenTo e1 e2 e3) =
482 data TickTransState = TT { modName :: String
483 , declPath :: [String]
485 , mixEntries :: [MixEntry]
489 data TM a = TM { unTM :: TickTransState -> (a,TickTransState) }
491 instance Monad TM where
492 return a = TM $ \ st -> (a,st)
493 (TM m) >>= k = TM $ \ st -> case m st of
494 (r1,st1) -> unTM (k r1) st1
496 --addTick :: LHsExpr Id -> TM (LHsExpr Id)
497 --addTick e = TM $ \ uq -> (e,succ uq,[(uq,getLoc e)])
499 addPathEntry :: String -> TM a -> TM a
500 addPathEntry nm (TM m) = TM $ \ st -> case m (st { declPath = declPath st ++ [nm] }) of
501 (r,st') -> (r,st' { declPath = declPath st })
503 getPathEntry :: TM [String]
504 getPathEntry = TM $ \ st -> (declPath st,st)
506 -- the tick application inherits the source position of its
507 -- expression argument to support nested box allocations
508 allocTickBox :: BoxLabel -> SrcSpan -> TM (LHsExpr Id -> LHsExpr Id)
509 allocTickBox boxLabel pos | Just hpcPos <- mkHpcPos pos = TM $ \ st ->
510 let me = (hpcPos,boxLabel)
513 in ( \ (L pos e) -> L pos $ HsTick c (L pos e)
514 , st {tickBoxCount=c+1,mixEntries=me:mes}
516 allocTickBox boxLabel e = return id
518 -- the tick application inherits the source position of its
519 -- expression argument to support nested box allocations
520 allocATickBox :: BoxLabel -> SrcSpan -> TM (Maybe Int)
521 allocATickBox boxLabel pos | Just hpcPos <- mkHpcPos pos = TM $ \ st ->
522 let me = (hpcPos,boxLabel)
526 , st {tickBoxCount=c+1,mixEntries=me:mes}
528 allocATickBox boxLabel e = return Nothing
530 allocBinTickBox :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id)
531 allocBinTickBox boxLabel (L pos e) | Just hpcPos <- mkHpcPos pos = TM $ \ st ->
532 let meT = (hpcPos,boxLabel True)
533 meF = (hpcPos,boxLabel False)
534 meE = (hpcPos,ExpBox)
539 then ( L pos $ HsTick c $ L pos $ HsBinTick (c+1) (c+2) (L pos e)
540 -- notice that F and T are reversed,
541 -- because we are building the list in
543 , st {tickBoxCount=c+3,mixEntries=meF:meT:meE:mes}
546 ( L pos $ HsTick c $ L pos e
547 , st {tickBoxCount=c+1,mixEntries=meE:mes}
550 allocBinTickBox boxLabel e = return e
552 mkHpcPos :: SrcSpan -> Maybe HpcPos
554 | not (isGoodSrcSpan pos) = Nothing
555 | start == end = Nothing -- no actual location
556 | otherwise = Just hpcPos
558 start = srcSpanStart pos
560 hpcPos = toHpcPos ( srcLocLine start
566 hpcSrcSpan = mkGeneralSrcSpan (FSLIT("Haskell Program Coverage internals"))
571 matchesOneOfMany :: [LMatch Id] -> Bool
572 matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1
574 matchCount (L _ (Match _pats _ty (GRHSs grhss _binds))) = length grhss
579 ---------------------------------------------------------------
580 -- Datatypes and file-access routines for the per-module (.mix)
581 -- indexes used by Hpc.
582 -- Colin Runciman and Andy Gill, June 2006
583 ---------------------------------------------------------------
585 -- a module index records the attributes of each tick-box that has
586 -- been introduced in that module, accessed by tick-number position
590 FilePath -- location of original file
591 Integer -- time (in seconds) of original file's last update, since 1970.
592 Int -- tab stop value
593 [MixEntry] -- entries
596 -- We would rather use ClockTime in Mix, but ClockTime has no Read instance in 6.4 and before,
597 -- but does in 6.6. Definining the instance for ClockTime here is the Wrong Thing to do,
598 -- because if some other program also defined that instance, we will not be able to compile.
600 type MixEntry = (HpcPos, BoxLabel)
602 data BoxLabel = ExpBox
604 | TopLevelBox [String]
609 | ExternalBox String HpcPos
610 -- ^The position was generated from the named file/module,
611 -- with the stated position (inside the named file/module).
612 -- The HpcPos inside this MixEntry refers to the generated Haskell location.
613 deriving (Read, Show)
615 mixCreate :: String -> String -> Mix -> IO ()
616 mixCreate dirName modName mix =
617 writeFile (mixName dirName modName) (show mix)
619 mixName :: FilePath -> String -> String
620 mixName dirName name = dirName ++ "/" ++ name ++ ".mix"
622 getModificationTime' :: FilePath -> IO Integer
623 getModificationTime' file = do
624 (TOD sec _) <- System.Directory.getModificationTime file
627 -- a program index records module names and numbers of tick-boxes
628 -- introduced in each module that has been transformed for coverage
630 data HpcPos = P !Int !Int !Int !Int deriving (Eq)
632 toHpcPos :: (Int,Int,Int,Int) -> HpcPos
633 toHpcPos (l1,c1,l2,c2) = P l1 c1 l2 c2
635 instance Show HpcPos where
636 show (P l1 c1 l2 c2) = show l1 ++ ':' : show c1 ++ '-' : show l2 ++ ':' : show c2
638 instance Read HpcPos where
639 readsPrec _i pos = [(toHpcPos (read l1,read c1,read l2,read c2),after)]
641 (before,after) = span (/= ',') pos
642 (lhs,rhs) = case span (/= '-') before of
643 (lhs,'-':rhs) -> (lhs,rhs)
644 (lhs,"") -> (lhs,lhs)
645 (l1,':':c1) = span (/= ':') lhs
646 (l2,':':c2) = span (/= ':') rhs