2 % (c) The University of Glasgow, 2000-2006
4 \section[Finder]{Module Finder}
13 findExposedPackageModule,
17 addHomeModuleToFinder,
21 findObjectLinkableMaybe,
34 import PrelNames ( gHC_PRIM )
35 import DynFlags ( DynFlags(..), isOneShot, GhcMode(..) )
39 import Maybes ( expectJust )
41 import Distribution.Package hiding (PackageId)
42 import Data.IORef ( IORef, writeIORef, readIORef, modifyIORef )
44 import System.Directory
45 import System.FilePath
48 import System.Time ( ClockTime )
51 type FileExt = String -- Filename extension
52 type BaseName = String -- Basename of file
54 -- -----------------------------------------------------------------------------
57 -- The Finder provides a thin filesystem abstraction to the rest of
58 -- the compiler. For a given module, it can tell you where the
59 -- source, interface, and object files for that module live.
61 -- It does *not* know which particular package a module lives in. Use
62 -- Packages.lookupModuleInAllPackages for that.
64 -- -----------------------------------------------------------------------------
67 -- remove all the home modules from the cache; package modules are
68 -- assumed to not move around during a session.
69 flushFinderCaches :: HscEnv -> IO ()
70 flushFinderCaches hsc_env = do
71 writeIORef fc_ref emptyUFM
72 flushModLocationCache this_pkg mlc_ref
74 this_pkg = thisPackage (hsc_dflags hsc_env)
75 fc_ref = hsc_FC hsc_env
76 mlc_ref = hsc_MLC hsc_env
78 flushModLocationCache :: PackageId -> IORef ModLocationCache -> IO ()
79 flushModLocationCache this_pkg ref = do
81 writeIORef ref $! filterFM is_ext fm
83 where is_ext mod _ | modulePackageId mod /= this_pkg = True
86 addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
87 addToFinderCache ref key val = modifyIORef ref $ \c -> addToUFM c key val
89 addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
90 addToModLocationCache ref key val = modifyIORef ref $ \c -> addToFM c key val
92 removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
93 removeFromFinderCache ref key = modifyIORef ref $ \c -> delFromUFM c key
95 removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
96 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
98 lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
99 lookupFinderCache ref key = do
101 return $! lookupUFM c key
103 lookupModLocationCache :: IORef ModLocationCache -> Module
104 -> IO (Maybe ModLocation)
105 lookupModLocationCache ref key = do
107 return $! lookupFM c key
109 -- -----------------------------------------------------------------------------
110 -- The two external entry points
112 -- | Locate a module that was imported by the user. We have the
113 -- module's name, and possibly a package name. Without a package
114 -- name, this function will use the search path and the known exposed
115 -- packages to find the module, if a package is specified then only
116 -- that package is searched for the module.
118 findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
119 findImportedModule hsc_env mod_name mb_pkg =
121 Nothing -> unqual_import
122 Just pkg | pkg == fsLit "this" -> home_import -- "this" is special
123 | otherwise -> pkg_import
125 home_import = findHomeModule hsc_env mod_name
127 pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg
129 unqual_import = home_import
131 findExposedPackageModule hsc_env mod_name Nothing
133 -- | Locate a specific 'Module'. The purpose of this function is to
134 -- create a 'ModLocation' for a given 'Module', that is to find out
135 -- where the files associated with this module live. It is used when
136 -- reading the interface for a module mentioned by another interface,
137 -- for example (a "system import").
139 findExactModule :: HscEnv -> Module -> IO FindResult
140 findExactModule hsc_env mod =
141 let dflags = hsc_dflags hsc_env in
142 if modulePackageId mod == thisPackage dflags
143 then findHomeModule hsc_env (moduleName mod)
144 else findPackageModule hsc_env mod
146 -- -----------------------------------------------------------------------------
149 orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
150 this `orIfNotFound` or_this = do
153 NotFound places1 _mb_pkg1 mod_hiddens1 pkg_hiddens1 -> do
156 NotFound places2 mb_pkg2 mod_hiddens2 pkg_hiddens2 ->
157 return (NotFound (places1 ++ places2)
158 mb_pkg2 -- snd arg is the package search
159 (mod_hiddens1 ++ mod_hiddens2)
160 (pkg_hiddens1 ++ pkg_hiddens2))
161 _other -> return res2
165 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
166 homeSearchCache hsc_env mod_name do_this = do
167 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
169 Just result -> return result
172 addToFinderCache (hsc_FC hsc_env) mod_name result
174 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
178 findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString
180 findExposedPackageModule hsc_env mod_name mb_pkg
181 -- not found in any package:
182 | null found_exposed = return (NotFound [] Nothing mod_hiddens pkg_hiddens)
183 -- found in just one exposed package:
184 | [(pkg_conf, _)] <- found_exposed
185 = let pkgid = mkPackageId (package pkg_conf) in
186 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
188 = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
190 dflags = hsc_dflags hsc_env
191 found = lookupModuleInAllPackages dflags mod_name
193 for_this_pkg = filter ((`matches` mb_pkg) . fst) found
195 found_exposed = [ (pkg_conf,exposed_mod)
196 | x@(pkg_conf,exposed_mod) <- for_this_pkg,
199 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
201 mod_hiddens = [ mkPackageId (package pkg_conf)
202 | (pkg_conf,False) <- found ]
204 pkg_hiddens = [ mkPackageId (package pkg_conf)
205 | (pkg_conf,_) <- found, not (exposed pkg_conf) ]
207 _pkg_conf `matches` Nothing = True
208 pkg_conf `matches` Just pkg =
209 case packageName pkg_conf of
210 PackageName n -> pkg == mkFastString n
213 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
214 modLocationCache hsc_env mod do_this = do
215 mb_loc <- lookupModLocationCache mlc mod
217 Just loc -> return (Found loc mod)
221 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
225 mlc = hsc_MLC hsc_env
227 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
228 addHomeModuleToFinder hsc_env mod_name loc = do
229 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
230 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
231 addToModLocationCache (hsc_MLC hsc_env) mod loc
234 uncacheModule :: HscEnv -> ModuleName -> IO ()
235 uncacheModule hsc_env mod = do
236 let this_pkg = thisPackage (hsc_dflags hsc_env)
237 removeFromFinderCache (hsc_FC hsc_env) mod
238 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
240 -- -----------------------------------------------------------------------------
241 -- The internal workers
243 -- | Search for a module in the home package only.
244 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
245 findHomeModule hsc_env mod_name =
246 homeSearchCache hsc_env mod_name $
248 dflags = hsc_dflags hsc_env
249 home_path = importPaths dflags
251 mod = mkModule (thisPackage dflags) mod_name
254 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
255 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
258 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
259 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
262 -- In compilation manager modes, we look for source files in the home
263 -- package because we can compile these automatically. In one-shot
264 -- compilation mode we look for .hi and .hi-boot files only.
265 exts | isOneShot (ghcMode dflags) = hi_exts
266 | otherwise = source_exts
269 -- special case for GHC.Prim; we won't find it in the filesystem.
270 -- This is important only when compiling the base package (where GHC.Prim
271 -- is a home module).
273 then return (Found (error "GHC.Prim ModLocation") mod)
276 searchPathExts home_path mod exts
279 -- | Search for a module in external packages only.
280 findPackageModule :: HscEnv -> Module -> IO FindResult
281 findPackageModule hsc_env mod = do
283 dflags = hsc_dflags hsc_env
284 pkg_id = modulePackageId mod
285 pkg_map = pkgIdMap (pkgState dflags)
287 case lookupPackage pkg_map pkg_id of
288 Nothing -> return (NoPackage pkg_id)
289 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
291 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
292 findPackageModule_ hsc_env mod pkg_conf =
293 modLocationCache hsc_env mod $
295 -- special case for GHC.Prim; we won't find it in the filesystem.
297 then return (Found (error "GHC.Prim ModLocation") mod)
301 dflags = hsc_dflags hsc_env
302 tag = buildTag dflags
304 -- hi-suffix for packages depends on the build tag.
305 package_hisuf | null tag = "hi"
306 | otherwise = tag ++ "_hi"
308 mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf
310 import_dirs = importDirs pkg_conf
311 -- we never look for a .hi-boot file in an external package;
312 -- .hi-boot files only make sense for the home package.
315 [one] | MkDepend <- ghcMode dflags -> do
316 -- there's only one place that this .hi file can be, so
317 -- don't bother looking for it.
318 let basename = moduleNameSlashes (moduleName mod)
319 loc <- mk_hi_loc one basename
320 return (Found loc mod)
322 searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)]
324 -- -----------------------------------------------------------------------------
325 -- General path searching
328 :: [FilePath] -- paths to search
329 -> Module -- module name
332 FilePath -> BaseName -> IO ModLocation -- action
337 searchPathExts paths mod exts
338 = do result <- search to_search
340 hPutStrLn stderr (showSDoc $
341 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
342 , nest 2 (vcat (map text paths))
344 Succeeded (loc, p) -> text "Found" <+> ppr loc
345 Failed fs -> text "not found"])
350 basename = moduleNameSlashes (moduleName mod)
352 to_search :: [(FilePath, IO ModLocation)]
353 to_search = [ (file, fn path basename)
356 let base | path == "." = basename
357 | otherwise = path </> basename
361 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod))
363 search ((file, mk_result) : rest) = do
364 b <- doesFileExist file
366 then do { loc <- mk_result; return (Found loc mod) }
369 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
370 -> FilePath -> BaseName -> IO ModLocation
371 mkHomeModLocationSearched dflags mod suff path basename = do
372 mkHomeModLocation2 dflags mod (path </> basename) suff
374 -- -----------------------------------------------------------------------------
375 -- Constructing a home module location
377 -- This is where we construct the ModLocation for a module in the home
378 -- package, for which we have a source file. It is called from three
381 -- (a) Here in the finder, when we are searching for a module to import,
382 -- using the search path (-i option).
384 -- (b) The compilation manager, when constructing the ModLocation for
385 -- a "root" module (a source file named explicitly on the command line
386 -- or in a :load command in GHCi).
388 -- (c) The driver in one-shot mode, when we need to construct a
389 -- ModLocation for a source file named on the command-line.
394 -- The name of the module
397 -- (a): The search path component where the source file was found.
401 -- (a): (moduleNameSlashes mod)
402 -- (b) and (c): The filename of the source file, minus its extension
405 -- The filename extension of the source file (usually "hs" or "lhs").
407 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
408 mkHomeModLocation dflags mod src_filename = do
409 let (basename,extension) = splitExtension src_filename
410 mkHomeModLocation2 dflags mod basename extension
412 mkHomeModLocation2 :: DynFlags
414 -> FilePath -- Of source module, without suffix
417 mkHomeModLocation2 dflags mod src_basename ext = do
418 let mod_basename = moduleNameSlashes mod
420 obj_fn <- mkObjPath dflags src_basename mod_basename
421 hi_fn <- mkHiPath dflags src_basename mod_basename
423 return (ModLocation{ ml_hs_file = Just (src_basename <.> ext),
425 ml_obj_file = obj_fn })
427 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
429 mkHiOnlyModLocation dflags hisuf path basename
430 = do let full_basename = path </> basename
431 obj_fn <- mkObjPath dflags full_basename basename
432 return ModLocation{ ml_hs_file = Nothing,
433 ml_hi_file = full_basename <.> hisuf,
434 -- Remove the .hi-boot suffix from
435 -- hi_file, if it had one. We always
436 -- want the name of the real .hi file
437 -- in the ml_hi_file field.
441 -- | Constructs the filename of a .o file for a given source file.
442 -- Does /not/ check whether the .o file exists
445 -> FilePath -- the filename of the source file, minus the extension
446 -> String -- the module name with dots replaced by slashes
448 mkObjPath dflags basename mod_basename
450 odir = objectDir dflags
451 osuf = objectSuf dflags
453 obj_basename | Just dir <- odir = dir </> mod_basename
454 | otherwise = basename
456 return (obj_basename <.> osuf)
458 -- | Constructs the filename of a .hi file for a given source file.
459 -- Does /not/ check whether the .hi file exists
462 -> FilePath -- the filename of the source file, minus the extension
463 -> String -- the module name with dots replaced by slashes
465 mkHiPath dflags basename mod_basename
470 hi_basename | Just dir <- hidir = dir </> mod_basename
471 | otherwise = basename
473 return (hi_basename <.> hisuf)
476 -- -----------------------------------------------------------------------------
477 -- Filenames of the stub files
479 -- We don't have to store these in ModLocations, because they can be derived
480 -- from other available information, and they're only rarely needed.
486 -> (FilePath,FilePath,FilePath)
488 mkStubPaths dflags mod location
490 stubdir = stubDir dflags
492 mod_basename = moduleNameSlashes mod
493 src_basename = dropExtension $ expectJust "mkStubPaths"
494 (ml_hs_file location)
497 | Just dir <- stubdir = dir </> mod_basename
498 | otherwise = src_basename
500 stub_basename = stub_basename0 ++ "_stub"
502 obj = ml_obj_file location
503 osuf = objectSuf dflags
504 stub_obj_base = dropTail (length osuf + 1) obj ++ "_stub"
505 -- NB. not takeFileName, see #3093
507 (stub_basename <.> "c",
508 stub_basename <.> "h",
509 stub_obj_base <.> objectSuf dflags)
511 -- -----------------------------------------------------------------------------
512 -- findLinkable isn't related to the other stuff in here,
513 -- but there's no other obvious place for it
515 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
516 findObjectLinkableMaybe mod locn
517 = do let obj_fn = ml_obj_file locn
518 maybe_obj_time <- modificationTimeIfExists obj_fn
519 case maybe_obj_time of
520 Nothing -> return Nothing
521 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
523 -- Make an object linkable when we know the object file exists, and we know
524 -- its modification time.
525 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
526 findObjectLinkable mod obj_fn obj_time = do
527 let stub_fn = (dropExtension obj_fn ++ "_stub") <.> "o"
528 stub_exist <- doesFileExist stub_fn
530 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
531 else return (LM obj_time mod [DotO obj_fn])
533 -- -----------------------------------------------------------------------------
536 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
537 cannotFindModule = cantFindErr (sLit "Could not find module")
538 (sLit "Ambiguous module name")
540 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
541 cannotFindInterface = cantFindErr (sLit "Failed to load interface for")
542 (sLit "Ambiguous interface for")
544 cantFindErr :: LitString -> LitString -> DynFlags -> ModuleName -> FindResult
546 cantFindErr _ multiple_found _ mod_name (FoundMultiple pkgs)
547 = hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
548 sep [ptext (sLit "it was found in multiple packages:"),
549 hsep (map (text.packageIdString) pkgs)]
551 cantFindErr cannot_find _ dflags mod_name find_result
552 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
556 = case find_result of
558 -> ptext (sLit "no package matching") <+> quotes (ppr pkg) <+>
559 ptext (sLit "was found")
561 NotFound files mb_pkg mod_hiddens pkg_hiddens
562 | Just pkg <- mb_pkg, pkg /= thisPackage dflags
563 -> not_found_in_package pkg files
565 | null files && null mod_hiddens && null pkg_hiddens
566 -> ptext (sLit "it is not a module in the current program, or in any known package.")
569 -> vcat (map pkg_hidden pkg_hiddens) $$
570 vcat (map mod_hidden mod_hiddens) $$
573 NotFoundInPackage pkg
574 -> ptext (sLit "it is not in package") <+> quotes (ppr pkg)
576 _ -> panic "cantFindErr"
578 build_tag = buildTag dflags
580 not_found_in_package pkg files
583 build = if build_tag == "p" then "profiling"
584 else "\"" ++ build_tag ++ "\""
586 ptext (sLit "Perhaps you haven't installed the ") <> text build <>
587 ptext (sLit " libraries for package ") <> quotes (ppr pkg) <> char '?' $$
591 = ptext (sLit "There are files missing in the ") <> quotes (ppr pkg) <>
592 ptext (sLit " package,") $$
593 ptext (sLit "try running 'ghc-pkg check'.") $$
598 | verbosity dflags < 3 =
599 ptext (sLit "Use -v to see a list of the files searched for.")
601 hang (ptext (sLit "locations searched:")) 2 $ vcat (map text files)
604 ptext (sLit "it is a member of the hidden package") <+> quotes (ppr pkg)
607 ptext (sLit "it is a hidden module in the package") <+> quotes (ppr pkg)