PageRenderTime 60ms CodeModel.GetById 14ms RepoModel.GetById 7ms app.codeStats 0ms

/utils/ghctags/Main.hs

https://github.com/kgardas/ghc
Haskell | 355 lines | 267 code | 49 blank | 39 comment | 14 complexity | c77537a43ffbb2040767c83bbc2e5d09 MD5 | raw file
  1. {-# LANGUAGE PatternGuards, ScopedTypeVariables #-}
  2. module Main where
  3. import Prelude hiding ( mod, id, mapM )
  4. import GHC hiding (flags)
  5. --import Packages
  6. import HscTypes ( isBootSummary )
  7. import Digraph ( flattenSCCs )
  8. import DriverPhases ( isHaskellSrcFilename )
  9. import HscTypes ( msHsFilePath )
  10. import Name ( getOccString )
  11. --import ErrUtils ( printBagOfErrors )
  12. import Panic ( panic )
  13. import DynFlags ( defaultLogAction )
  14. import Bag
  15. import Exception
  16. import FastString
  17. import MonadUtils ( liftIO )
  18. import SrcLoc
  19. -- Every GHC comes with Cabal anyways, so this is not a bad new dependency
  20. import Distribution.Simple.GHC ( ghcOptions )
  21. import Distribution.Simple.Configure ( getPersistBuildConfig )
  22. import Distribution.PackageDescription ( library, libBuildInfo )
  23. import Distribution.Simple.LocalBuildInfo ( localPkgDescr, buildDir, libraryConfig )
  24. import Control.Monad hiding (mapM)
  25. import System.Environment
  26. import System.Console.GetOpt
  27. import System.Exit
  28. import System.IO
  29. import Data.List as List hiding ( group )
  30. import Data.Traversable (mapM)
  31. import Data.Map ( Map )
  32. import qualified Data.Map as M
  33. --import UniqFM
  34. --import Debug.Trace
  35. -- search for definitions of things
  36. -- we do this by parsing the source and grabbing top-level definitions
  37. -- We generate both CTAGS and ETAGS format tags files
  38. -- The former is for use in most sensible editors, while EMACS uses ETAGS
  39. ----------------------------------
  40. ---- CENTRAL DATA TYPES ----------
  41. type FileName = String
  42. type ThingName = String -- name of a defined entity in a Haskell program
  43. -- A definition we have found (we know its containing module, name, and location)
  44. data FoundThing = FoundThing ModuleName ThingName RealSrcLoc
  45. -- Data we have obtained from a file (list of things we found)
  46. data FileData = FileData FileName [FoundThing] (Map Int String)
  47. --- invariant (not checked): every found thing has a source location in that file?
  48. ------------------------------
  49. -------- MAIN PROGRAM --------
  50. main :: IO ()
  51. main = do
  52. progName <- getProgName
  53. let usageString =
  54. "Usage: " ++ progName ++ " [OPTION...] [-- GHC OPTION... --] [files...]"
  55. args <- getArgs
  56. let (ghcArgs', ourArgs, unbalanced) = splitArgs args
  57. let (flags, filenames, errs) = getOpt Permute options ourArgs
  58. let (hsfiles, otherfiles) = List.partition isHaskellSrcFilename filenames
  59. let ghc_topdir = case [ d | FlagTopDir d <- flags ] of
  60. [] -> ""
  61. (x:_) -> x
  62. mapM_ (\n -> putStr $ "Warning: ignoring non-Haskellish file " ++ n ++ "\n")
  63. otherfiles
  64. if unbalanced || errs /= [] || elem FlagHelp flags || hsfiles == []
  65. then do
  66. putStr $ unlines errs
  67. putStr $ usageInfo usageString options
  68. exitWith (ExitFailure 1)
  69. else return ()
  70. ghcArgs <- case [ d | FlagUseCabalConfig d <- flags ] of
  71. [distPref] -> do
  72. cabalOpts <- flagsFromCabal distPref
  73. return (cabalOpts ++ ghcArgs')
  74. [] ->
  75. return ghcArgs'
  76. _ -> error "Too many --use-cabal-config flags"
  77. print ghcArgs
  78. let modes = getMode flags
  79. let openFileMode = if elem FlagAppend flags
  80. then AppendMode
  81. else WriteMode
  82. ctags_hdl <- if CTags `elem` modes
  83. then Just `liftM` openFile "tags" openFileMode
  84. else return Nothing
  85. etags_hdl <- if ETags `elem` modes
  86. then Just `liftM` openFile "TAGS" openFileMode
  87. else return Nothing
  88. GHC.defaultErrorHandler defaultLogAction $
  89. runGhc (Just ghc_topdir) $ do
  90. --liftIO $ print "starting up session"
  91. dflags <- getSessionDynFlags
  92. (pflags, unrec, warns) <- parseDynamicFlags dflags{ verbosity=1 }
  93. (map noLoc ghcArgs)
  94. unless (null unrec) $
  95. liftIO $ putStrLn $ "Unrecognised options:\n" ++ show (map unLoc unrec)
  96. liftIO $ mapM_ putStrLn (map unLoc warns)
  97. let dflags2 = pflags { hscTarget = HscNothing } -- don't generate anything
  98. -- liftIO $ print ("pkgDB", case (pkgDatabase dflags2) of Nothing -> 0
  99. -- Just m -> sizeUFM m)
  100. _ <- setSessionDynFlags dflags2
  101. --liftIO $ print (length pkgs)
  102. GHC.defaultCleanupHandler dflags2 $ do
  103. targetsAtOneGo hsfiles (ctags_hdl,etags_hdl)
  104. mapM_ (mapM (liftIO . hClose)) [ctags_hdl, etags_hdl]
  105. ----------------------------------------------
  106. ---------- ARGUMENT PROCESSING --------------
  107. data Flag
  108. = FlagETags
  109. | FlagCTags
  110. | FlagBoth
  111. | FlagAppend
  112. | FlagHelp
  113. | FlagTopDir FilePath
  114. | FlagUseCabalConfig FilePath
  115. | FlagFilesFromCabal
  116. deriving (Ord, Eq, Show)
  117. -- ^Represents options passed to the program
  118. data Mode = ETags | CTags deriving Eq
  119. getMode :: [Flag] -> [Mode]
  120. getMode fs = go (concatMap modeLike fs)
  121. where go [] = [ETags,CTags]
  122. go [x] = [x]
  123. go more = nub more
  124. modeLike FlagETags = [ETags]
  125. modeLike FlagCTags = [CTags]
  126. modeLike FlagBoth = [ETags,CTags]
  127. modeLike _ = []
  128. splitArgs :: [String] -> ([String], [String], Bool)
  129. -- ^Pull out arguments between -- for GHC
  130. splitArgs args0 = split [] [] False args0
  131. where split ghc' tags' unbal ("--" : args) = split tags' ghc' (not unbal) args
  132. split ghc' tags' unbal (arg : args) = split ghc' (arg:tags') unbal args
  133. split ghc' tags' unbal [] = (reverse ghc', reverse tags', unbal)
  134. options :: [OptDescr Flag]
  135. -- supports getopt
  136. options = [ Option "" ["topdir"]
  137. (ReqArg FlagTopDir "DIR") "root of GHC installation (optional)"
  138. , Option "c" ["ctags"]
  139. (NoArg FlagCTags) "generate CTAGS file (ctags)"
  140. , Option "e" ["etags"]
  141. (NoArg FlagETags) "generate ETAGS file (etags)"
  142. , Option "b" ["both"]
  143. (NoArg FlagBoth) ("generate both CTAGS and ETAGS")
  144. , Option "a" ["append"]
  145. (NoArg FlagAppend) ("append to existing CTAGS and/or ETAGS file(s)")
  146. , Option "" ["use-cabal-config"]
  147. (ReqArg FlagUseCabalConfig "DIR") "use local cabal configuration from dist dir"
  148. , Option "" ["files-from-cabal"]
  149. (NoArg FlagFilesFromCabal) "use files from cabal"
  150. , Option "h" ["help"] (NoArg FlagHelp) "This help"
  151. ]
  152. flagsFromCabal :: FilePath -> IO [String]
  153. flagsFromCabal distPref = do
  154. lbi <- getPersistBuildConfig distPref
  155. let pd = localPkgDescr lbi
  156. case (library pd, libraryConfig lbi) of
  157. (Just lib, Just clbi) ->
  158. let bi = libBuildInfo lib
  159. odir = buildDir lbi
  160. opts = ghcOptions lbi bi clbi odir
  161. in return opts
  162. _ -> error "no library"
  163. ----------------------------------------------------------------
  164. --- LOADING HASKELL SOURCE
  165. --- (these bits actually run the compiler and produce abstract syntax)
  166. safeLoad :: LoadHowMuch -> Ghc SuccessFlag
  167. -- like GHC.load, but does not stop process on exception
  168. safeLoad mode = do
  169. _dflags <- getSessionDynFlags
  170. ghandle (\(e :: SomeException) -> liftIO (print e) >> return Failed ) $
  171. handleSourceError (\e -> printException e >> return Failed) $
  172. load mode
  173. targetsAtOneGo :: [FileName] -> (Maybe Handle, Maybe Handle) -> Ghc ()
  174. -- load a list of targets
  175. targetsAtOneGo hsfiles handles = do
  176. targets <- mapM (\f -> guessTarget f Nothing) hsfiles
  177. setTargets targets
  178. modgraph <- depanal [] False
  179. let mods = flattenSCCs $ topSortModuleGraph False modgraph Nothing
  180. graphData mods handles
  181. fileTarget :: FileName -> Target
  182. fileTarget filename = Target (TargetFile filename Nothing) True Nothing
  183. ---------------------------------------------------------------
  184. ----- CRAWLING ABSTRACT SYNTAX TO SNAFFLE THE DEFINITIONS -----
  185. graphData :: ModuleGraph -> (Maybe Handle, Maybe Handle) -> Ghc ()
  186. graphData graph handles = do
  187. mapM_ foundthings graph
  188. where foundthings ms =
  189. let filename = msHsFilePath ms
  190. modname = moduleName $ ms_mod ms
  191. in handleSourceError (\e -> do
  192. printException e
  193. liftIO $ exitWith (ExitFailure 1)) $
  194. do liftIO $ putStrLn ("loading " ++ filename)
  195. mod <- loadModule =<< typecheckModule =<< parseModule ms
  196. case mod of
  197. _ | isBootSummary ms -> return ()
  198. _ | Just s <- renamedSource mod ->
  199. liftIO (writeTagsData handles =<< fileData filename modname s)
  200. _otherwise ->
  201. liftIO $ exitWith (ExitFailure 1)
  202. fileData :: FileName -> ModuleName -> RenamedSource -> IO FileData
  203. fileData filename modname (group, _imports, _lie, _doc) = do
  204. -- lie is related to type checking and so is irrelevant
  205. -- imports contains import declarations and no definitions
  206. -- doc and haddock seem haddock-related; let's hope to ignore them
  207. ls <- lines `fmap` readFile filename
  208. let line_map = M.fromAscList $ zip [1..] ls
  209. line_map' <- evaluate line_map
  210. return $ FileData filename (boundValues modname group) line_map'
  211. boundValues :: ModuleName -> HsGroup Name -> [FoundThing]
  212. -- ^Finds all the top-level definitions in a module
  213. boundValues mod group =
  214. let vals = case hs_valds group of
  215. ValBindsOut nest _sigs ->
  216. [ x | (_rec, binds) <- nest
  217. , bind <- bagToList binds
  218. , x <- boundThings mod bind ]
  219. _other -> error "boundValues"
  220. tys = [ n | ns <- map hsTyClDeclBinders (concat (hs_tyclds group))
  221. , n <- map found ns ]
  222. fors = concat $ map forBound (hs_fords group)
  223. where forBound lford = case unLoc lford of
  224. ForeignImport n _ _ -> [found n]
  225. ForeignExport { } -> []
  226. in vals ++ tys ++ fors
  227. where found = foundOfLName mod
  228. startOfLocated :: Located a -> RealSrcLoc
  229. startOfLocated lHs = case getLoc lHs of
  230. RealSrcSpan l -> realSrcSpanStart l
  231. UnhelpfulSpan _ -> panic "startOfLocated UnhelpfulSpan"
  232. foundOfLName :: ModuleName -> Located Name -> FoundThing
  233. foundOfLName mod id = FoundThing mod (getOccString $ unLoc id) (startOfLocated id)
  234. boundThings :: ModuleName -> LHsBind Name -> [FoundThing]
  235. boundThings modname lbinding =
  236. case unLoc lbinding of
  237. FunBind { fun_id = id } -> [thing id]
  238. PatBind { pat_lhs = lhs } -> patThings lhs []
  239. VarBind { var_id = id } -> [FoundThing modname (getOccString id) (startOfLocated lbinding)]
  240. AbsBinds { } -> [] -- nothing interesting in a type abstraction
  241. where thing = foundOfLName modname
  242. patThings lpat tl =
  243. let loc = startOfLocated lpat
  244. lid id = FoundThing modname (getOccString id) loc
  245. in case unLoc lpat of
  246. WildPat _ -> tl
  247. VarPat name -> lid name : tl
  248. LazyPat p -> patThings p tl
  249. AsPat id p -> patThings p (thing id : tl)
  250. ParPat p -> patThings p tl
  251. BangPat p -> patThings p tl
  252. ListPat ps _ -> foldr patThings tl ps
  253. TuplePat ps _ _ -> foldr patThings tl ps
  254. PArrPat ps _ -> foldr patThings tl ps
  255. ConPatIn _ conargs -> conArgs conargs tl
  256. ConPatOut _ _ _ _ conargs _ -> conArgs conargs tl
  257. LitPat _ -> tl
  258. NPat _ _ _ -> tl -- form of literal pattern?
  259. NPlusKPat id _ _ _ -> thing id : tl
  260. SigPatIn p _ -> patThings p tl
  261. SigPatOut p _ -> patThings p tl
  262. _ -> error "boundThings"
  263. conArgs (PrefixCon ps) tl = foldr patThings tl ps
  264. conArgs (RecCon (HsRecFields { rec_flds = flds })) tl
  265. = foldr (\f tl' -> patThings (hsRecFieldArg f) tl') tl flds
  266. conArgs (InfixCon p1 p2) tl = patThings p1 $ patThings p2 tl
  267. -- stuff for dealing with ctags output format
  268. writeTagsData :: (Maybe Handle, Maybe Handle) -> FileData -> IO ()
  269. writeTagsData (mb_ctags_hdl, mb_etags_hdl) fd = do
  270. maybe (return ()) (\hdl -> writectagsfile hdl fd) mb_ctags_hdl
  271. maybe (return ()) (\hdl -> writeetagsfile hdl fd) mb_etags_hdl
  272. writectagsfile :: Handle -> FileData -> IO ()
  273. writectagsfile ctagsfile filedata = do
  274. let things = getfoundthings filedata
  275. mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing False x) things
  276. mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing True x) things
  277. getfoundthings :: FileData -> [FoundThing]
  278. getfoundthings (FileData _filename things _src_lines) = things
  279. dumpthing :: Bool -> FoundThing -> String
  280. dumpthing showmod (FoundThing modname name loc) =
  281. fullname ++ "\t" ++ filename ++ "\t" ++ (show line)
  282. where line = srcLocLine loc
  283. filename = unpackFS $ srcLocFile loc
  284. fullname = if showmod then moduleNameString modname ++ "." ++ name
  285. else name
  286. -- stuff for dealing with etags output format
  287. writeetagsfile :: Handle -> FileData -> IO ()
  288. writeetagsfile etagsfile = hPutStr etagsfile . e_dumpfiledata
  289. e_dumpfiledata :: FileData -> String
  290. e_dumpfiledata (FileData filename things line_map) =
  291. "\x0c\n" ++ filename ++ "," ++ (show thingslength) ++ "\n" ++ thingsdump
  292. where
  293. thingsdump = concat $ map (e_dumpthing line_map) things
  294. thingslength = length thingsdump
  295. e_dumpthing :: Map Int String -> FoundThing -> String
  296. e_dumpthing src_lines (FoundThing modname name loc) =
  297. tagline name ++ tagline (moduleNameString modname ++ "." ++ name)
  298. where tagline n = src_code ++ "\x7f"
  299. ++ n ++ "\x01"
  300. ++ (show line) ++ "," ++ (show $ column) ++ "\n"
  301. line = srcLocLine loc
  302. column = srcLocCol loc
  303. src_code = case M.lookup line src_lines of
  304. Just l -> take (column + length name) l
  305. Nothing -> --trace (show ("not found: ", moduleNameString modname, name, line, column))
  306. name