Debian Codegraph @

src-bin-881/Clash/GHCi/UI/Info.hs

raw
1 {-# OPTIONS_GHC -Wno-name-shadowing #-}
2 {-# LANGUAGE LambdaCase #-}
3 {-# LANGUAGE OverloadedStrings #-}
4 {-# LANGUAGE RankNTypes #-}
5
6 -- | Get information on modules, expressions, and identifiers
7 module Clash.GHCi.UI.Info
8 ( ModInfo(..)
9 , SpanInfo(..)
10 , spanInfoFromRealSrcSpan
11 , collectInfo
12 , findLoc
13 , findNameUses
14 , findType
15 , getModInfo
16 ) where
17
18 import Control.Exception
19 import Control.Monad
20 import Control.Monad.Trans.Class
21 import Control.Monad.Trans.Except
22 import Control.Monad.Trans.Maybe
23 import Data.Data
24 import Data.Function
25 import Data.List
26 import Data.Map.Strict (Map)
27 import qualified Data.Map.Strict as M
28 import Data.Maybe
29 import Data.Time
30 import Prelude hiding (mod,(<>))
31 import System.Directory
32
33 import qualified CoreUtils
34 import Desugar
35 import DynFlags (HasDynFlags(..))
36 import FastString
37 import GHC
38 import GhcMonad
39 import Name
40 import NameSet
41 import Outputable
42 import SrcLoc
43 import TcHsSyn
44 import Var
45
46 -- | Info about a module. This information is generated every time a
47 -- module is loaded.
48 data ModInfo = ModInfo
49 { modinfoSummary :: !ModSummary
50 -- ^ Summary generated by GHC. Can be used to access more
51 -- information about the module.
52 , modinfoSpans :: [SpanInfo]
53 -- ^ Generated set of information about all spans in the
54 -- module that correspond to some kind of identifier for
55 -- which there will be type info and/or location info.
56 , modinfoInfo :: !ModuleInfo
57 -- ^ Again, useful from GHC for accessing information
58 -- (exports, instances, scope) from a module.
59 , modinfoLastUpdate :: !UTCTime
60 -- ^ The timestamp of the file used to generate this record.
61 }
62
63 -- | Type of some span of source code. Most of these fields are
64 -- unboxed but Haddock doesn't show that.
65 data SpanInfo = SpanInfo
66 { spaninfoSrcSpan :: {-# UNPACK #-} !RealSrcSpan
67 -- ^ The span we associate information with
68 , spaninfoType :: !(Maybe Type)
69 -- ^ The 'Type' associated with the span
70 , spaninfoVar :: !(Maybe Id)
71 -- ^ The actual 'Var' associated with the span, if
72 -- any. This can be useful for accessing a variety of
73 -- information about the identifier such as module,
74 -- locality, definition location, etc.
75 }
76
77 -- | Test whether second span is contained in (or equal to) first span.
78 -- This is basically 'containsSpan' for 'SpanInfo'
79 containsSpanInfo :: SpanInfo -> SpanInfo -> Bool
80 containsSpanInfo = containsSpan `on` spaninfoSrcSpan
81
82 -- | Filter all 'SpanInfo' which are contained in 'SpanInfo'
83 spaninfosWithin :: [SpanInfo] -> SpanInfo -> [SpanInfo]
84 spaninfosWithin spans' si = filter (si `containsSpanInfo`) spans'
85
86 -- | Construct a 'SpanInfo' from a 'RealSrcSpan' and optionally a
87 -- 'Type' and an 'Id' (for 'spaninfoType' and 'spaninfoVar'
88 -- respectively)
89 spanInfoFromRealSrcSpan :: RealSrcSpan -> Maybe Type -> Maybe Id -> SpanInfo
90 spanInfoFromRealSrcSpan spn mty mvar =
91 SpanInfo spn mty mvar
92
93 -- | Convenience wrapper around 'spanInfoFromRealSrcSpan' which needs
94 -- only a 'RealSrcSpan'
95 spanInfoFromRealSrcSpan' :: RealSrcSpan -> SpanInfo
96 spanInfoFromRealSrcSpan' s = spanInfoFromRealSrcSpan s Nothing Nothing
97
98 -- | Convenience wrapper around 'srcSpanFile' which results in a 'FilePath'
99 srcSpanFilePath :: RealSrcSpan -> FilePath
100 srcSpanFilePath = unpackFS . srcSpanFile
101
102 -- | Try to find the location of the given identifier at the given
103 -- position in the module.
104 findLoc :: GhcMonad m
105 => Map ModuleName ModInfo
106 -> RealSrcSpan
107 -> String
108 -> ExceptT SDoc m (ModInfo,Name,SrcSpan)
109 findLoc infos span0 string = do
110 name <- maybeToExceptT "Couldn't guess that module name. Does it exist?" $
111 guessModule infos (srcSpanFilePath span0)
112
113 info <- maybeToExceptT "No module info for current file! Try loading it?" $
114 MaybeT $ pure $ M.lookup name infos
115
116 name' <- findName infos span0 info string
117
118 case getSrcSpan name' of
119 UnhelpfulSpan{} -> do
120 throwE ("Found a name, but no location information." <+>
121 "The module is:" <+>
122 maybe "<unknown>" (ppr . moduleName)
123 (nameModule_maybe name'))
124
125 span' -> return (info,name',span')
126
127 -- | Find any uses of the given identifier in the codebase.
128 findNameUses :: (GhcMonad m)
129 => Map ModuleName ModInfo
130 -> RealSrcSpan
131 -> String
132 -> ExceptT SDoc m [SrcSpan]
133 findNameUses infos span0 string =
134 locToSpans <$> findLoc infos span0 string
135 where
136 locToSpans (modinfo,name',span') =
137 stripSurrounding (span' : map toSrcSpan spans)
138 where
139 toSrcSpan = RealSrcSpan . spaninfoSrcSpan
140 spans = filter ((== Just name') . fmap getName . spaninfoVar)
141 (modinfoSpans modinfo)
142
143 -- | Filter out redundant spans which surround/contain other spans.
144 stripSurrounding :: [SrcSpan] -> [SrcSpan]
145 stripSurrounding xs = filter (not . isRedundant) xs
146 where
147 isRedundant x = any (x `strictlyContains`) xs
148
149 (RealSrcSpan s1) `strictlyContains` (RealSrcSpan s2)
150 = s1 /= s2 && s1 `containsSpan` s2
151 _ `strictlyContains` _ = False
152
153 -- | Try to resolve the name located at the given position, or
154 -- otherwise resolve based on the current module's scope.
155 findName :: GhcMonad m
156 => Map ModuleName ModInfo
157 -> RealSrcSpan
158 -> ModInfo
159 -> String
160 -> ExceptT SDoc m Name
161 findName infos span0 mi string =
162 case resolveName (modinfoSpans mi) (spanInfoFromRealSrcSpan' span0) of
163 Nothing -> tryExternalModuleResolution
164 Just name ->
165 case getSrcSpan name of
166 UnhelpfulSpan {} -> tryExternalModuleResolution
167 RealSrcSpan {} -> return (getName name)
168 where
169 tryExternalModuleResolution =
170 case find (matchName $ mkFastString string)
171 (fromMaybe [] (modInfoTopLevelScope (modinfoInfo mi))) of
172 Nothing -> throwE "Couldn't resolve to any modules."
173 Just imported -> resolveNameFromModule infos imported
174
175 matchName :: FastString -> Name -> Bool
176 matchName str name =
177 str ==
178 occNameFS (getOccName name)
179
180 -- | Try to resolve the name from another (loaded) module's exports.
181 resolveNameFromModule :: GhcMonad m
182 => Map ModuleName ModInfo
183 -> Name
184 -> ExceptT SDoc m Name
185 resolveNameFromModule infos name = do
186 modL <- maybe (throwE $ "No module for" <+> ppr name) return $
187 nameModule_maybe name
188
189 info <- maybe (throwE (ppr (moduleUnitId modL) <> ":" <>
190 ppr modL)) return $
191 M.lookup (moduleName modL) infos
192
193 maybe (throwE "No matching export in any local modules.") return $
194 find (matchName name) (modInfoExports (modinfoInfo info))
195 where
196 matchName :: Name -> Name -> Bool
197 matchName x y = occNameFS (getOccName x) ==
198 occNameFS (getOccName y)
199
200 -- | Try to resolve the type display from the given span.
201 resolveName :: [SpanInfo] -> SpanInfo -> Maybe Var
202 resolveName spans' si = listToMaybe $ mapMaybe spaninfoVar $
203 reverse spans' `spaninfosWithin` si
204
205 -- | Try to find the type of the given span.
206 findType :: GhcMonad m
207 => Map ModuleName ModInfo
208 -> RealSrcSpan
209 -> String
210 -> ExceptT SDoc m (ModInfo, Type)
211 findType infos span0 string = do
212 name <- maybeToExceptT "Couldn't guess that module name. Does it exist?" $
213 guessModule infos (srcSpanFilePath span0)
214
215 info <- maybeToExceptT "No module info for current file! Try loading it?" $
216 MaybeT $ pure $ M.lookup name infos
217
218 case resolveType (modinfoSpans info) (spanInfoFromRealSrcSpan' span0) of
219 Nothing -> (,) info <$> lift (exprType TM_Inst string)
220 Just ty -> return (info, ty)
221 where
222 -- | Try to resolve the type display from the given span.
223 resolveType :: [SpanInfo] -> SpanInfo -> Maybe Type
224 resolveType spans' si = listToMaybe $ mapMaybe spaninfoType $
225 reverse spans' `spaninfosWithin` si
226
227 -- | Guess a module name from a file path.
228 guessModule :: GhcMonad m
229 => Map ModuleName ModInfo -> FilePath -> MaybeT m ModuleName
230 guessModule infos fp = do
231 target <- lift $ guessTarget fp Nothing
232 case targetId target of
233 TargetModule mn -> return mn
234 TargetFile fp' _ -> guessModule' fp'
235 where
236 guessModule' :: GhcMonad m => FilePath -> MaybeT m ModuleName
237 guessModule' fp' = case findModByFp fp' of
238 Just mn -> return mn
239 Nothing -> do
240 fp'' <- liftIO (makeRelativeToCurrentDirectory fp')
241
242 target' <- lift $ guessTarget fp'' Nothing
243 case targetId target' of
244 TargetModule mn -> return mn
245 _ -> MaybeT . pure $ findModByFp fp''
246
247 findModByFp :: FilePath -> Maybe ModuleName
248 findModByFp fp' = fst <$> find ((Just fp' ==) . mifp) (M.toList infos)
249 where
250 mifp :: (ModuleName, ModInfo) -> Maybe FilePath
251 mifp = ml_hs_file . ms_location . modinfoSummary . snd
252
253
254 -- | Collect type info data for the loaded modules.
255 collectInfo :: (GhcMonad m) => Map ModuleName ModInfo -> [ModuleName]
256 -> m (Map ModuleName ModInfo)
257 collectInfo ms loaded = do
258 df <- getDynFlags
259 liftIO (filterM cacheInvalid loaded) >>= \case
260 [] -> return ms
261 invalidated -> do
262 liftIO (putStrLn ("Collecting type info for " ++
263 show (length invalidated) ++
264 " module(s) ... "))
265
266 foldM (go df) ms invalidated
267 where
268 go df m name = do { info <- getModInfo name; return (M.insert name info m) }
269 `gcatch`
270 (\(e :: SomeException) -> do
271 liftIO $ putStrLn
272 $ showSDocForUser df alwaysQualify
273 $ "Error while getting type info from" <+>
274 ppr name <> ":" <+> text (show e)
275 return m)
276
277 cacheInvalid name = case M.lookup name ms of
278 Nothing -> return True
279 Just mi -> do
280 let fp = srcFilePath (modinfoSummary mi)
281 last' = modinfoLastUpdate mi
282 current <- getModificationTime fp
283 exists <- doesFileExist fp
284 if exists
285 then return $ current /= last'
286 else return True
287
288 -- | Get the source file path from a ModSummary.
289 -- If the .hs file is missing, and the .o file exists,
290 -- we return the .o file path.
291 srcFilePath :: ModSummary -> FilePath
292 srcFilePath modSum = fromMaybe obj_fp src_fp
293 where
294 src_fp = ml_hs_file ms_loc
295 obj_fp = ml_obj_file ms_loc
296 ms_loc = ms_location modSum
297
298 -- | Get info about the module: summary, types, etc.
299 getModInfo :: (GhcMonad m) => ModuleName -> m ModInfo
300 getModInfo name = do
301 m <- getModSummary name
302 p <- parseModule m
303 typechecked <- typecheckModule p
304 allTypes <- processAllTypeCheckedModule typechecked
305 let i = tm_checked_module_info typechecked
306 ts <- liftIO $ getModificationTime $ srcFilePath m
307 return (ModInfo m allTypes i ts)
308
309 -- | Get ALL source spans in the module.
310 processAllTypeCheckedModule :: forall m . GhcMonad m => TypecheckedModule
311 -> m [SpanInfo]
312 processAllTypeCheckedModule tcm = do
313 bts <- mapM getTypeLHsBind $ listifyAllSpans tcs
314 ets <- mapM getTypeLHsExpr $ listifyAllSpans tcs
315 pts <- mapM getTypeLPat $ listifyAllSpans tcs
316 return $ mapMaybe toSpanInfo
317 $ sortBy cmpSpan
318 $ catMaybes (bts ++ ets ++ pts)
319 where
320 tcs = tm_typechecked_source tcm
321
322 -- | Extract 'Id', 'SrcSpan', and 'Type' for 'LHsBind's
323 getTypeLHsBind :: LHsBind GhcTc -> m (Maybe (Maybe Id,SrcSpan,Type))
324 getTypeLHsBind (dL->L _spn FunBind{fun_id = pid,fun_matches = MG _ _ _})
325 = pure $ Just (Just (unLoc pid),getLoc pid,varType (unLoc pid))
326 getTypeLHsBind _ = pure Nothing
327
328 -- | Extract 'Id', 'SrcSpan', and 'Type' for 'LHsExpr's
329 getTypeLHsExpr :: LHsExpr GhcTc -> m (Maybe (Maybe Id,SrcSpan,Type))
330 getTypeLHsExpr e = do
331 hs_env <- getSession
332 (_,mbe) <- liftIO $ deSugarExpr hs_env e
333 return $ fmap (\expr -> (mid, getLoc e, CoreUtils.exprType expr)) mbe
334 where
335 mid :: Maybe Id
336 mid | HsVar _ (dL->L _ i) <- unwrapVar (unLoc e) = Just i
337 | otherwise = Nothing
338
339 unwrapVar (HsWrap _ _ var) = var
340 unwrapVar e' = e'
341
342 -- | Extract 'Id', 'SrcSpan', and 'Type' for 'LPats's
343 getTypeLPat :: LPat GhcTc -> m (Maybe (Maybe Id,SrcSpan,Type))
344 getTypeLPat (dL->L spn pat) =
345 pure (Just (getMaybeId pat,spn,hsPatType pat))
346 where
347 getMaybeId (VarPat _ (dL->L _ vid)) = Just vid
348 getMaybeId _ = Nothing
349
350 -- | Get ALL source spans in the source.
351 listifyAllSpans :: (HasSrcSpan a , Typeable a) => TypecheckedSource -> [a]
352 listifyAllSpans = everythingAllSpans (++) [] ([] `mkQ` (\x -> [x | p x]))
353 where
354 p (dL->L spn _) = isGoodSrcSpan spn
355
356 -- | Variant of @syb@'s @everything@ (which summarises all nodes
357 -- in top-down, left-to-right order) with a stop-condition on 'NameSet's
358 everythingAllSpans :: (r -> r -> r) -> r -> GenericQ r -> GenericQ r
359 everythingAllSpans k z f x
360 | (False `mkQ` (const True :: NameSet -> Bool)) x = z
361 | otherwise = foldl k (f x) (gmapQ (everythingAllSpans k z f) x)
362
363 cmpSpan (_,a,_) (_,b,_)
364 | a `isSubspanOf` b = LT
365 | b `isSubspanOf` a = GT
366 | otherwise = EQ
367
368 -- | Pretty print the types into a 'SpanInfo'.
369 toSpanInfo :: (Maybe Id,SrcSpan,Type) -> Maybe SpanInfo
370 toSpanInfo (n,RealSrcSpan spn,typ)
371 = Just $ spanInfoFromRealSrcSpan spn (Just typ) n
372 toSpanInfo _ = Nothing
373
374 -- helper stolen from @syb@ package
375 type GenericQ r = forall a. Data a => a -> r
376
377 mkQ :: (Typeable a, Typeable b) => r -> (b -> r) -> a -> r
378 (r `mkQ` br) a = maybe r br (cast a)