3 % (c) University of Glasgow, 2007
5 \section[Coverage]{@coverage@: the main function}
8 module Coverage (addCoverageTicksToBinds, hpcInitCode) where
32 import System.Directory ( createDirectoryIfMissing )
38 import Data.HashTable ( hashString )
40 import qualified Data.Map as Map
44 %************************************************************************
46 %* The main function: addCoverageTicksToBinds
48 %************************************************************************
51 addCoverageTicksToBinds
54 -> ModLocation -- of the current module
55 -> [TyCon] -- type constructor in this module
57 -> IO (LHsBinds Id, HpcInfo, ModBreaks)
59 addCoverageTicksToBinds dflags mod mod_loc tyCons binds =
60 case ml_hs_file mod_loc of
61 Nothing -> return (binds, emptyHpcInfo False, emptyModBreaks)
64 if "boot" `isSuffixOf` orig_file then return (binds, emptyHpcInfo False, emptyModBreaks) else do
66 -- Now, we try look for a file generated from a .hsc file to a .hs file, by peeking ahead.
68 let top_pos = catMaybes $ foldrBag (\ (L pos _) rest -> srcSpanFileName_maybe pos : rest) [] binds
69 let orig_file2 = case top_pos of
71 | ".hsc" `isSuffixOf` unpackFS file_name -> unpackFS file_name
74 let mod_name = moduleNameString (moduleName mod)
77 = unTM (addTickLHsBinds binds)
79 { fileName = mkFastString orig_file2
81 , inScope = emptyVarSet
82 , blackList = Map.fromList [ (getSrcSpan (tyConName tyCon),())
90 let entries = reverse $ mixEntries st
92 -- write the mix entries for this module
93 hashNo <- if opt_Hpc then do
94 let hpc_dir = hpcDir dflags
96 let hpc_mod_dir = if modulePackageId mod == mainPackageId
98 else hpc_dir ++ "/" ++ packageIdString (modulePackageId mod)
100 let tabStop = 1 -- <tab> counts as a normal char in GHC's location ranges.
101 createDirectoryIfMissing True hpc_mod_dir
102 modTime <- getModificationTime orig_file2
103 let entries' = [ (hpcPos, box)
104 | (span,_,_,box) <- entries, hpcPos <- [mkHpcPos span] ]
105 when (length entries' /= tickBoxCount st) $ do
106 panic "the number of .mix entries are inconsistent"
107 let hashNo = mixHash orig_file2 modTime tabStop entries'
108 mixCreate hpc_mod_dir mod_name
109 $ Mix orig_file2 modTime (toHash hashNo) tabStop entries'
114 -- Todo: use proper src span type
115 breakArray <- newBreakArray $ length entries
117 let locsTicks = listArray (0,tickBoxCount st-1)
118 [ span | (span,_,_,_) <- entries ]
119 varsTicks = listArray (0,tickBoxCount st-1)
120 [ vars | (_,_,vars,_) <- entries ]
121 declsTicks= listArray (0,tickBoxCount st-1)
122 [ decls | (_,decls,_,_) <- entries ]
123 modBreaks = emptyModBreaks
124 { modBreaks_flags = breakArray
125 , modBreaks_locs = locsTicks
126 , modBreaks_vars = varsTicks
127 , modBreaks_decls = declsTicks
130 doIfSet_dyn dflags Opt_D_dump_hpc $ do
131 printDump (pprLHsBinds binds1)
133 return (binds1, HpcInfo (tickBoxCount st) hashNo, modBreaks)
138 liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a)
139 liftL f (L loc a) = do
143 addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id)
144 addTickLHsBinds binds = mapBagM addTickLHsBind binds
146 addTickLHsBind :: LHsBind Id -> TM (LHsBind Id)
147 addTickLHsBind (L pos bind@(AbsBinds { abs_binds = binds })) = do
148 binds' <- addTickLHsBinds binds
149 return $ L pos $ bind { abs_binds = binds' }
150 addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do
151 let name = getOccString id
152 decl_path <- getPathEntry
154 (fvs, (MatchGroup matches' ty)) <-
157 addTickMatchGroup (fun_matches funBind)
159 blackListed <- isBlackListed pos
161 -- Todo: we don't want redundant ticks on simple pattern bindings
162 -- We don't want to generate code for blacklisted positions
163 if blackListed || (not opt_Hpc && isSimplePatBind funBind)
165 return $ L pos $ funBind { fun_matches = MatchGroup matches' ty
169 tick_no <- allocATickBox (if null decl_path
170 then TopLevelBox [name]
171 else LocalBox (decl_path ++ [name]))
174 return $ L pos $ funBind { fun_matches = MatchGroup matches' ty
178 -- a binding is a simple pattern binding if it is a funbind with zero patterns
179 isSimplePatBind :: HsBind a -> Bool
180 isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0
182 -- TODO: Revisit this
183 addTickLHsBind (L pos (pat@(PatBind { pat_rhs = rhs }))) = do
185 rhs' <- addPathEntry name $ addTickGRHSs False rhs
187 decl_path <- getPathEntry
188 tick_me <- allocTickBox (if null decl_path
189 then TopLevelBox [name]
190 else LocalBox (name : decl_path))
192 return $ L pos $ pat { pat_rhs = rhs' }
194 -- Only internal stuff, not from source, uses VarBind, so we ignore it.
195 addTickLHsBind var_bind@(L _ (VarBind {})) = return var_bind
197 -- Add a tick to the expression no matter what it is. There is one exception:
198 -- for the debugger, if the expression is a 'let', then we don't want to add
199 -- a tick here because there will definititely be a tick on the body anyway.
200 addTickLHsExprAlways :: LHsExpr Id -> TM (LHsExpr Id)
201 addTickLHsExprAlways (L pos e0)
202 | not opt_Hpc, HsLet _ _ <- e0 = addTickLHsExprNever (L pos e0)
203 | otherwise = allocTickBox (ExpBox False) pos $ addTickHsExpr e0
205 addTickLHsExprNeverOrAlways :: LHsExpr Id -> TM (LHsExpr Id)
206 addTickLHsExprNeverOrAlways e
207 | opt_Hpc = addTickLHsExprNever e
208 | otherwise = addTickLHsExprAlways e
210 addTickLHsExprNeverOrMaybe :: LHsExpr Id -> TM (LHsExpr Id)
211 addTickLHsExprNeverOrMaybe e
212 | opt_Hpc = addTickLHsExprNever e
213 | otherwise = addTickLHsExpr e
215 -- version of addTick that does not actually add a tick,
216 -- because the scope of this tick is completely subsumed by
218 addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id)
219 addTickLHsExprNever (L pos e0) = do
220 e1 <- addTickHsExpr e0
223 -- selectively add ticks to interesting expressions
224 addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id)
225 addTickLHsExpr (L pos e0) = do
226 if opt_Hpc || isGoodBreakExpr e0
228 allocTickBox (ExpBox False) pos $ addTickHsExpr e0
230 e1 <- addTickHsExpr e0
233 -- general heuristic: expressions which do not denote values are good break points
234 isGoodBreakExpr :: HsExpr Id -> Bool
235 isGoodBreakExpr (HsApp {}) = True
236 isGoodBreakExpr (OpApp {}) = True
237 isGoodBreakExpr (NegApp {}) = True
238 isGoodBreakExpr (HsCase {}) = True
239 isGoodBreakExpr (HsIf {}) = True
240 isGoodBreakExpr (RecordCon {}) = True
241 isGoodBreakExpr (RecordUpd {}) = True
242 isGoodBreakExpr (ArithSeq {}) = True
243 isGoodBreakExpr (PArrSeq {}) = True
244 isGoodBreakExpr _other = False
246 addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id)
247 addTickLHsExprOptAlt oneOfMany (L pos e0)
248 | not opt_Hpc = addTickLHsExpr (L pos e0)
250 allocTickBox (ExpBox oneOfMany) pos $
253 addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id)
254 addBinTickLHsExpr boxLabel (L pos e0) =
255 allocBinTickBox boxLabel pos $
258 addTickHsExpr :: HsExpr Id -> TM (HsExpr Id)
259 addTickHsExpr e@(HsVar id) = do freeVar id; return e
260 addTickHsExpr e@(HsIPVar _) = return e
261 addTickHsExpr e@(HsOverLit _) = return e
262 addTickHsExpr e@(HsLit _) = return e
263 addTickHsExpr (HsLam matchgroup) =
264 liftM HsLam (addTickMatchGroup matchgroup)
265 addTickHsExpr (HsApp e1 e2) =
266 liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2)
267 addTickHsExpr (OpApp e1 e2 fix e3) =
270 (addTickLHsExprNever e2)
273 addTickHsExpr (NegApp e neg) =
276 (addTickSyntaxExpr hpcSrcSpan neg)
277 addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprNeverOrMaybe e)
278 addTickHsExpr (SectionL e1 e2) =
282 addTickHsExpr (SectionR e1 e2) =
286 addTickHsExpr (ExplicitTuple es boxity) =
288 (mapM addTickTupArg es)
290 addTickHsExpr (HsCase e mgs) =
293 (addTickMatchGroup mgs)
294 addTickHsExpr (HsIf cnd e1 e2 e3) =
296 (addBinTickLHsExpr (BinBox CondBinBox) e1)
297 (addTickLHsExprOptAlt True e2)
298 (addTickLHsExprOptAlt True e3)
299 addTickHsExpr (HsLet binds e) =
300 bindLocals (collectLocalBinders binds) $
302 (addTickHsLocalBinds binds) -- to think about: !patterns.
303 (addTickLHsExprNeverOrAlways e)
304 addTickHsExpr (HsDo cxt stmts last_exp srcloc) = do
305 (stmts', last_exp') <- addTickLStmts' forQual stmts
306 (addTickLHsExpr last_exp)
307 return (HsDo cxt stmts' last_exp' srcloc)
309 forQual = case cxt of
310 ListComp -> Just $ BinBox QualBinBox
312 addTickHsExpr (ExplicitList ty es) =
315 (mapM (addTickLHsExpr) es)
316 addTickHsExpr (ExplicitPArr ty es) =
319 (mapM (addTickLHsExpr) es)
320 addTickHsExpr (RecordCon id ty rec_binds) =
324 (addTickHsRecordBinds rec_binds)
325 addTickHsExpr (RecordUpd e rec_binds cons tys1 tys2) =
328 (addTickHsRecordBinds rec_binds)
329 (return cons) (return tys1) (return tys2)
331 addTickHsExpr (ExprWithTySigOut e ty) =
332 liftM2 ExprWithTySigOut
333 (addTickLHsExprNever e) -- No need to tick the inner expression
334 -- for expressions with signatures
336 addTickHsExpr (ArithSeq ty arith_seq) =
339 (addTickArithSeqInfo arith_seq)
340 addTickHsExpr (HsTickPragma _ (L pos e0)) = do
341 e2 <- allocTickBox (ExpBox False) pos $
344 addTickHsExpr (PArrSeq ty arith_seq) =
347 (addTickArithSeqInfo arith_seq)
348 addTickHsExpr (HsSCC nm e) =
352 addTickHsExpr (HsCoreAnn nm e) =
356 addTickHsExpr e@(HsBracket {}) = return e
357 addTickHsExpr e@(HsBracketOut {}) = return e
358 addTickHsExpr e@(HsSpliceE {}) = return e
359 addTickHsExpr (HsProc pat cmdtop) =
362 (liftL (addTickHsCmdTop) cmdtop)
363 addTickHsExpr (HsWrap w e) =
366 (addTickHsExpr e) -- explicitly no tick on inside
368 addTickHsExpr (HsArrApp e1 e2 ty1 arr_ty lr) =
376 addTickHsExpr (HsArrForm e fix cmdtop) =
380 (mapM (liftL (addTickHsCmdTop)) cmdtop)
382 addTickHsExpr e@(HsType _) = return e
384 -- Others dhould never happen in expression content.
385 addTickHsExpr e = pprPanic "addTickHsExpr" (ppr e)
387 addTickTupArg :: HsTupArg Id -> TM (HsTupArg Id)
388 addTickTupArg (Present e) = do { e' <- addTickLHsExpr e; return (Present e') }
389 addTickTupArg (Missing ty) = return (Missing ty)
391 addTickMatchGroup :: MatchGroup Id -> TM (MatchGroup Id)
392 addTickMatchGroup (MatchGroup matches ty) = do
393 let isOneOfMany = matchesOneOfMany matches
394 matches' <- mapM (liftL (addTickMatch isOneOfMany)) matches
395 return $ MatchGroup matches' ty
397 addTickMatch :: Bool -> Match Id -> TM (Match Id)
398 addTickMatch isOneOfMany (Match pats opSig gRHSs) =
399 bindLocals (collectPatsBinders pats) $ do
400 gRHSs' <- addTickGRHSs isOneOfMany gRHSs
401 return $ Match pats opSig gRHSs'
403 addTickGRHSs :: Bool -> GRHSs Id -> TM (GRHSs Id)
404 addTickGRHSs isOneOfMany (GRHSs guarded local_binds) = do
405 bindLocals binders $ do
406 local_binds' <- addTickHsLocalBinds local_binds
407 guarded' <- mapM (liftL (addTickGRHS isOneOfMany)) guarded
408 return $ GRHSs guarded' local_binds'
410 binders = collectLocalBinders local_binds
412 addTickGRHS :: Bool -> GRHS Id -> TM (GRHS Id)
413 addTickGRHS isOneOfMany (GRHS stmts expr) = do
414 (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts
415 (if opt_Hpc then addTickLHsExprOptAlt isOneOfMany expr
416 else addTickLHsExprAlways expr)
417 return $ GRHS stmts' expr'
419 addTickLStmts :: (Maybe (Bool -> BoxLabel)) -> [LStmt Id] -> TM [LStmt Id]
420 addTickLStmts isGuard stmts = do
421 (stmts, _) <- addTickLStmts' isGuard stmts (return ())
424 addTickLStmts' :: (Maybe (Bool -> BoxLabel)) -> [LStmt Id] -> TM a
425 -> TM ([LStmt Id], a)
426 addTickLStmts' isGuard lstmts res
427 = bindLocals binders $ do
428 lstmts' <- mapM (liftL (addTickStmt isGuard)) lstmts
432 binders = collectLStmtsBinders lstmts
434 addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id -> TM (Stmt Id)
435 addTickStmt _isGuard (BindStmt pat e bind fail) = do
438 (addTickLHsExprAlways e)
439 (addTickSyntaxExpr hpcSrcSpan bind)
440 (addTickSyntaxExpr hpcSrcSpan fail)
441 addTickStmt isGuard (ExprStmt e bind' ty) = do
444 (addTickSyntaxExpr hpcSrcSpan bind')
446 addTickStmt _isGuard (LetStmt binds) = do
448 (addTickHsLocalBinds binds)
449 addTickStmt isGuard (ParStmt pairs) = do
451 (mapM (addTickStmtAndBinders isGuard) pairs)
453 addTickStmt isGuard (TransformStmt stmts ids usingExpr maybeByExpr) = do
455 (addTickLStmts isGuard stmts)
457 (addTickLHsExprAlways usingExpr)
458 (addTickMaybeByLHsExpr maybeByExpr)
460 addTickStmt isGuard (GroupStmt stmts binderMap by using) = do
462 (addTickLStmts isGuard stmts)
464 (fmapMaybeM addTickLHsExprAlways by)
465 (fmapEitherM addTickLHsExprAlways (addTickSyntaxExpr hpcSrcSpan) using)
467 addTickStmt isGuard stmt@(RecStmt {})
468 = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt)
469 ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt)
470 ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt)
471 ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt)
472 ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret'
473 , recS_mfix_fn = mfix', recS_bind_fn = bind' }) }
475 addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id)
476 addTick isGuard e | Just fn <- isGuard = addBinTickLHsExpr fn e
477 | otherwise = addTickLHsExprAlways e
479 addTickStmtAndBinders :: Maybe (Bool -> BoxLabel) -> ([LStmt Id], a)
480 -> TM ([LStmt Id], a)
481 addTickStmtAndBinders isGuard (stmts, ids) =
483 (addTickLStmts isGuard stmts)
486 addTickMaybeByLHsExpr :: Maybe (LHsExpr Id) -> TM (Maybe (LHsExpr Id))
487 addTickMaybeByLHsExpr maybeByExpr =
489 Nothing -> return Nothing
490 Just byExpr -> addTickLHsExprAlways byExpr >>= (return . Just)
492 addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id)
493 addTickHsLocalBinds (HsValBinds binds) =
495 (addTickHsValBinds binds)
496 addTickHsLocalBinds (HsIPBinds binds) =
498 (addTickHsIPBinds binds)
499 addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds
501 addTickHsValBinds :: HsValBindsLR Id a -> TM (HsValBindsLR Id b)
502 addTickHsValBinds (ValBindsOut binds sigs) =
504 (mapM (\ (rec,binds') ->
507 (addTickLHsBinds binds'))
510 addTickHsValBinds _ = panic "addTickHsValBinds"
512 addTickHsIPBinds :: HsIPBinds Id -> TM (HsIPBinds Id)
513 addTickHsIPBinds (IPBinds ipbinds dictbinds) =
515 (mapM (liftL (addTickIPBind)) ipbinds)
518 addTickIPBind :: IPBind Id -> TM (IPBind Id)
519 addTickIPBind (IPBind nm e) =
524 -- There is no location here, so we might need to use a context location??
525 addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id)
526 addTickSyntaxExpr pos x = do
527 L _ x' <- addTickLHsExpr (L pos x)
529 -- we do not walk into patterns.
530 addTickLPat :: LPat Id -> TM (LPat Id)
531 addTickLPat pat = return pat
533 addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id)
534 addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) =
541 addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id)
542 addTickLHsCmd (L pos c0) = do
543 c1 <- addTickHsCmd c0
546 addTickHsCmd :: HsCmd Id -> TM (HsCmd Id)
547 addTickHsCmd (HsLam matchgroup) =
548 liftM HsLam (addTickCmdMatchGroup matchgroup)
549 addTickHsCmd (HsApp e1 e2) =
550 liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2)
551 addTickHsCmd (OpApp e1 c2 fix c3) =
557 addTickHsCmd (HsPar e) = liftM HsPar (addTickLHsCmd e)
558 addTickHsCmd (HsCase e mgs) =
561 (addTickCmdMatchGroup mgs)
562 addTickHsCmd (HsIf cnd e1 c2 c3) =
564 (addBinTickLHsExpr (BinBox CondBinBox) e1)
567 addTickHsCmd (HsLet binds c) =
568 bindLocals (collectLocalBinders binds) $
570 (addTickHsLocalBinds binds) -- to think about: !patterns.
572 addTickHsCmd (HsDo cxt stmts last_exp srcloc) = do
573 (stmts', last_exp') <- addTickLCmdStmts' stmts (addTickLHsCmd last_exp)
574 return (HsDo cxt stmts' last_exp' srcloc)
576 addTickHsCmd (HsArrApp e1 e2 ty1 arr_ty lr) =
583 addTickHsCmd (HsArrForm e fix cmdtop) =
587 (mapM (liftL (addTickHsCmdTop)) cmdtop)
589 -- Others should never happen in a command context.
590 addTickHsCmd e = pprPanic "addTickHsCmd" (ppr e)
592 addTickCmdMatchGroup :: MatchGroup Id -> TM (MatchGroup Id)
593 addTickCmdMatchGroup (MatchGroup matches ty) = do
594 matches' <- mapM (liftL addTickCmdMatch) matches
595 return $ MatchGroup matches' ty
597 addTickCmdMatch :: Match Id -> TM (Match Id)
598 addTickCmdMatch (Match pats opSig gRHSs) =
599 bindLocals (collectPatsBinders pats) $ do
600 gRHSs' <- addTickCmdGRHSs gRHSs
601 return $ Match pats opSig gRHSs'
603 addTickCmdGRHSs :: GRHSs Id -> TM (GRHSs Id)
604 addTickCmdGRHSs (GRHSs guarded local_binds) = do
605 bindLocals binders $ do
606 local_binds' <- addTickHsLocalBinds local_binds
607 guarded' <- mapM (liftL addTickCmdGRHS) guarded
608 return $ GRHSs guarded' local_binds'
610 binders = collectLocalBinders local_binds
612 addTickCmdGRHS :: GRHS Id -> TM (GRHS Id)
613 addTickCmdGRHS (GRHS stmts cmd) = do
614 (stmts',expr') <- addTickLCmdStmts' stmts (addTickLHsCmd cmd)
615 return $ GRHS stmts' expr'
617 addTickLCmdStmts :: [LStmt Id] -> TM [LStmt Id]
618 addTickLCmdStmts stmts = do
619 (stmts, _) <- addTickLCmdStmts' stmts (return ())
622 addTickLCmdStmts' :: [LStmt Id] -> TM a -> TM ([LStmt Id], a)
623 addTickLCmdStmts' lstmts res
624 = bindLocals binders $ do
625 lstmts' <- mapM (liftL addTickCmdStmt) lstmts
629 binders = collectLStmtsBinders lstmts
631 addTickCmdStmt :: Stmt Id -> TM (Stmt Id)
632 addTickCmdStmt (BindStmt pat c bind fail) = do
638 addTickCmdStmt (ExprStmt c bind' ty) = do
643 addTickCmdStmt (LetStmt binds) = do
645 (addTickHsLocalBinds binds)
646 addTickCmdStmt stmt@(RecStmt {})
647 = do { stmts' <- addTickLCmdStmts (recS_stmts stmt)
648 ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt)
649 ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt)
650 ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt)
651 ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret'
652 , recS_mfix_fn = mfix', recS_bind_fn = bind' }) }
654 -- Others should never happen in a command context.
655 addTickCmdStmt stmt = pprPanic "addTickHsCmd" (ppr stmt)
657 addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id)
658 addTickHsRecordBinds (HsRecFields fields dd)
659 = do { fields' <- mapM process fields
660 ; return (HsRecFields fields' dd) }
662 process (HsRecField ids expr doc)
663 = do { expr' <- addTickLHsExpr expr
664 ; return (HsRecField ids expr' doc) }
666 addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id)
667 addTickArithSeqInfo (From e1) =
670 addTickArithSeqInfo (FromThen e1 e2) =
674 addTickArithSeqInfo (FromTo e1 e2) =
678 addTickArithSeqInfo (FromThenTo e1 e2 e3) =
686 data TickTransState = TT { tickBoxCount:: Int
687 , mixEntries :: [MixEntry_]
690 data TickTransEnv = TTE { fileName :: FastString
691 , declPath :: [String]
693 , blackList :: Map SrcSpan ()
698 type FreeVars = OccEnv Id
703 -- For breakpoints we want to collect the free variables of an
704 -- expression for pinning on the HsTick. We don't want to collect
705 -- *all* free variables though: in particular there's no point pinning
706 -- on free variables that are will otherwise be in scope at the GHCi
707 -- prompt, which means all top-level bindings. Unfortunately detecting
708 -- top-level bindings isn't easy (collectHsBindsBinders on the top-level
709 -- bindings doesn't do it), so we keep track of a set of "in-scope"
710 -- variables in addition to the free variables, and the former is used
711 -- to filter additions to the latter. This gives us complete control
712 -- over what free variables we track.
714 data TM a = TM { unTM :: TickTransEnv -> TickTransState -> (a,FreeVars,TickTransState) }
715 -- a combination of a state monad (TickTransState) and a writer
718 instance Monad TM where
719 return a = TM $ \ _env st -> (a,noFVs,st)
720 (TM m) >>= k = TM $ \ env st ->
723 case unTM (k r1) env st1 of
725 (r2, fv1 `plusOccEnv` fv2, st2)
727 -- getState :: TM TickTransState
728 -- getState = TM $ \ env st -> (st, noFVs, st)
730 -- setState :: (TickTransState -> TickTransState) -> TM ()
731 -- setState f = TM $ \ env st -> ((), noFVs, f st)
733 getEnv :: TM TickTransEnv
734 getEnv = TM $ \ env st -> (env, noFVs, st)
736 withEnv :: (TickTransEnv -> TickTransEnv) -> TM a -> TM a
737 withEnv f (TM m) = TM $ \ env st ->
739 (a, fvs, st') -> (a, fvs, st')
741 getFreeVars :: TM a -> TM (FreeVars, a)
743 = TM $ \ env st -> case m env st of (a, fv, st') -> ((fv,a), fv, st')
745 freeVar :: Id -> TM ()
746 freeVar id = TM $ \ env st ->
747 if id `elemVarSet` inScope env
748 then ((), unitOccEnv (nameOccName (idName id)) id, st)
751 addPathEntry :: String -> TM a -> TM a
752 addPathEntry nm = withEnv (\ env -> env { declPath = declPath env ++ [nm] })
754 getPathEntry :: TM [String]
755 getPathEntry = declPath `liftM` getEnv
757 getFileName :: TM FastString
758 getFileName = fileName `liftM` getEnv
760 sameFileName :: SrcSpan -> TM a -> TM a -> TM a
761 sameFileName pos out_of_scope in_scope = do
762 file_name <- getFileName
763 case srcSpanFileName_maybe pos of
765 | file_name == file_name2 -> in_scope
768 bindLocals :: [Id] -> TM a -> TM a
769 bindLocals new_ids (TM m)
771 case m env{ inScope = inScope env `extendVarSetList` new_ids } st of
772 (r, fv, st') -> (r, fv `delListFromOccEnv` occs, st')
773 where occs = [ nameOccName (idName id) | id <- new_ids ]
775 isBlackListed :: SrcSpan -> TM Bool
776 isBlackListed pos = TM $ \ env st ->
777 case Map.lookup pos (blackList env) of
778 Nothing -> (False,noFVs,st)
779 Just () -> (True,noFVs,st)
781 -- the tick application inherits the source position of its
782 -- expression argument to support nested box allocations
783 allocTickBox :: BoxLabel -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id)
784 allocTickBox boxLabel pos m | isGoodSrcSpan' pos =
786 (do e <- m; return (L pos e)) $ do
787 (fvs, e) <- getFreeVars m
789 let c = tickBoxCount st
792 me = (pos, declPath env, map (nameOccName.idName) ids, boxLabel)
794 ( L pos (HsTick c ids (L pos e))
796 , st {tickBoxCount=c+1,mixEntries=me:mes}
798 allocTickBox _boxLabel pos m = do e <- m; return (L pos e)
800 -- the tick application inherits the source position of its
801 -- expression argument to support nested box allocations
802 allocATickBox :: BoxLabel -> SrcSpan -> FreeVars -> TM (Maybe (Int,[Id]))
803 allocATickBox boxLabel pos fvs | isGoodSrcSpan' pos =
805 (return Nothing) $ TM $ \ env st ->
807 | null (declPath env), TopLevelBox x <- boxLabel = x
808 | otherwise = declPath env
809 me = (pos, mydecl_path, map (nameOccName.idName) ids, boxLabel)
815 , st {tickBoxCount=c+1, mixEntries=me:mes}
817 allocATickBox _boxLabel _pos _fvs = return Nothing
819 allocBinTickBox :: (Bool -> BoxLabel) -> SrcSpan -> TM (HsExpr Id)
821 allocBinTickBox boxLabel pos m
822 | not opt_Hpc = allocTickBox (ExpBox False) pos m
823 | isGoodSrcSpan' pos =
827 let meT = (pos,declPath env, [],boxLabel True)
828 meF = (pos,declPath env, [],boxLabel False)
829 meE = (pos,declPath env, [],ExpBox False)
833 ( L pos $ HsTick c [] $ L pos $ HsBinTick (c+1) (c+2) (L pos e)
834 -- notice that F and T are reversed,
835 -- because we are building the list in
838 , st {tickBoxCount=c+3 , mixEntries=meF:meT:meE:mes}
840 allocBinTickBox _boxLabel pos m = do e <- m; return (L pos e)
842 isGoodSrcSpan' :: SrcSpan -> Bool
844 | not (isGoodSrcSpan pos) = False
845 | start == end = False
848 start = srcSpanStart pos
851 mkHpcPos :: SrcSpan -> HpcPos
853 | not (isGoodSrcSpan' pos) = panic "bad source span; expected such spans to be filtered out"
856 start = srcSpanStart pos
858 hpcPos = toHpcPos ( srcLocLine start
864 hpcSrcSpan :: SrcSpan
865 hpcSrcSpan = mkGeneralSrcSpan (fsLit "Haskell Program Coverage internals")
870 matchesOneOfMany :: [LMatch Id] -> Bool
871 matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1
873 matchCount (L _ (Match _pats _ty (GRHSs grhss _binds))) = length grhss
878 type MixEntry_ = (SrcSpan, [String], [OccName], BoxLabel)
880 -- For the hash value, we hash everything: the file name,
881 -- the timestamp of the original source file, the tab stop,
882 -- and the mix entries. We cheat, and hash the show'd string.
883 -- This hash only has to be hashed at Mix creation time,
884 -- and is for sanity checking only.
886 mixHash :: FilePath -> Integer -> Int -> [MixEntry] -> Int
887 mixHash file tm tabstop entries = fromIntegral $ hashString
888 (show $ Mix file tm 0 tabstop entries)
891 %************************************************************************
895 %************************************************************************
897 Each module compiled with -fhpc declares an initialisation function of
898 the form `hpc_init_<module>()`, which is emitted into the _stub.c file
899 and annotated with __attribute__((constructor)) so that it gets
900 executed at startup time.
902 The function's purpose is to call hs_hpc_module to register this
903 module with the RTS, and it looks something like this:
905 static void hpc_init_Main(void) __attribute__((constructor));
906 static void hpc_init_Main(void)
907 {extern StgWord64 _hpc_tickboxes_Main_hpc[];
908 hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);}
911 hpcInitCode :: Module -> HpcInfo -> SDoc
912 hpcInitCode _ (NoHpcInfo {}) = empty
913 hpcInitCode this_mod (HpcInfo tickCount hashNo)
915 [ text "static void hpc_init_" <> ppr this_mod
916 <> text "(void) __attribute__((constructor));"
917 , text "static void hpc_init_" <> ppr this_mod <> text "(void)"
919 ptext (sLit "extern StgWord64 ") <> tickboxes <>
920 ptext (sLit "[]") <> semi,
921 ptext (sLit "hs_hpc_module") <>
922 parens (hcat (punctuate comma [
923 doubleQuotes full_name_str,
924 int tickCount, -- really StgWord32
925 int hashNo, -- really StgWord32
931 tickboxes = pprCLabel (mkHpcTicksLabel $ this_mod)
933 module_name = hcat (map (text.charToC) $
934 bytesFS (moduleNameFS (Module.moduleName this_mod)))
935 package_name = hcat (map (text.charToC) $
936 bytesFS (packageIdFS (modulePackageId this_mod)))
938 | modulePackageId this_mod == mainPackageId
941 = package_name <> char '/' <> module_name