PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/utils/ghctags/Main.hs

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