1module HpcUtils where
2
3import Trace.Hpc.Util (catchIO, HpcPos, fromHpcPos, readFileUtf8)
4import qualified Data.Map as Map
5import System.FilePath
6
7dropWhileEndLE :: (a -> Bool) -> [a] -> [a]
8-- Spec: dropWhileEndLE p = reverse . dropWhile p . reverse
9dropWhileEndLE p = foldr (\x r -> if null r && p x then [] else x:r) []
10
11-- turns \n into ' '
12-- | grab's the text behind a HpcPos;
13grabHpcPos :: Map.Map Int String -> HpcPos -> String
14grabHpcPos hsMap srcspan =
15         case lns of
16           [ln] -> (take ((c2 - c1) + 1) $ drop (c1 - 1) ln)
17           _ -> let lns1 = drop (c1 -1) (head lns) : tail lns
18                    lns2 = init lns1 ++ [take (c2 + 1) (last lns1) ]
19                 in foldl1 (\ xs ys -> xs ++ "\n" ++ ys) lns2
20  where (l1,c1,l2,c2) = fromHpcPos srcspan
21        lns = map (\ n -> case Map.lookup n hsMap of
22                           Just ln -> ln
23                           Nothing -> error $ "bad line number : " ++ show n
24                  ) [l1..l2]
25
26
27readFileFromPath :: (String -> IO String) -> String -> [String] -> IO String
28readFileFromPath _ filename@('/':_) _ = readFileUtf8 filename
29readFileFromPath err filename path0 = readTheFile path0
30  where
31        readTheFile [] = err $ "could not find " ++ show filename
32                                 ++ " in path " ++ show path0
33        readTheFile (dir:dirs) =
34                catchIO (readFileUtf8 (dir </> filename))
35                        (\ _ -> readTheFile dirs)
36