PageRenderTime 60ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/utils/ghctags/Main.hs

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