PageRenderTime 80ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/utils/ghctags/Main.hs

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