2 % (c) The University of Glasgow, 2000-2006
4 \section[Finder]{Module Finder}
13 findExposedPackageModule,
17 addHomeModuleToFinder,
21 findObjectLinkableMaybe,
34 import PrelNames ( gHC_PRIM )
39 import Maybes ( expectJust )
40 import Exception ( evaluate )
42 import Distribution.Text
43 import Distribution.Package hiding (PackageId)
44 import Data.IORef ( IORef, writeIORef, readIORef, atomicModifyIORef )
45 import System.Directory
46 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 -- Ideally the update to both caches be a single atomic operation.
72 writeIORef fc_ref emptyUFM
73 flushModLocationCache this_pkg mlc_ref
75 this_pkg = thisPackage (hsc_dflags hsc_env)
76 fc_ref = hsc_FC hsc_env
77 mlc_ref = hsc_MLC hsc_env
79 flushModLocationCache :: PackageId -> IORef ModLocationCache -> IO ()
80 flushModLocationCache this_pkg ref = do
81 atomicModifyIORef ref $ \fm -> (filterModuleEnv is_ext fm, ())
82 _ <- evaluate =<< readIORef ref
84 where is_ext mod _ | modulePackageId mod /= this_pkg = True
87 addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
88 addToFinderCache ref key val =
89 atomicModifyIORef ref $ \c -> (addToUFM c key val, ())
91 addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
92 addToModLocationCache ref key val =
93 atomicModifyIORef ref $ \c -> (extendModuleEnv c key val, ())
95 removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
96 removeFromFinderCache ref key =
97 atomicModifyIORef ref $ \c -> (delFromUFM c key, ())
99 removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
100 removeFromModLocationCache ref key =
101 atomicModifyIORef ref $ \c -> (delModuleEnv c key, ())
103 lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
104 lookupFinderCache ref key = do
106 return $! lookupUFM c key
108 lookupModLocationCache :: IORef ModLocationCache -> Module
109 -> IO (Maybe ModLocation)
110 lookupModLocationCache ref key = do
112 return $! lookupModuleEnv c key
114 -- -----------------------------------------------------------------------------
115 -- The two external entry points
117 -- | Locate a module that was imported by the user. We have the
118 -- module's name, and possibly a package name. Without a package
119 -- name, this function will use the search path and the known exposed
120 -- packages to find the module, if a package is specified then only
121 -- that package is searched for the module.
123 findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
124 findImportedModule hsc_env mod_name mb_pkg =
126 Nothing -> unqual_import
127 Just pkg | pkg == fsLit "this" -> home_import -- "this" is special
128 | otherwise -> pkg_import
130 home_import = findHomeModule hsc_env mod_name
132 pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg
134 unqual_import = home_import
136 findExposedPackageModule hsc_env mod_name Nothing
138 -- | Locate a specific 'Module'. The purpose of this function is to
139 -- create a 'ModLocation' for a given 'Module', that is to find out
140 -- where the files associated with this module live. It is used when
141 -- reading the interface for a module mentioned by another interface,
142 -- for example (a "system import").
144 findExactModule :: HscEnv -> Module -> IO FindResult
145 findExactModule hsc_env mod =
146 let dflags = hsc_dflags hsc_env in
147 if modulePackageId mod == thisPackage dflags
148 then findHomeModule hsc_env (moduleName mod)
149 else findPackageModule hsc_env mod
151 -- -----------------------------------------------------------------------------
154 orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
155 this `orIfNotFound` or_this = do
158 NotFound places1 _mb_pkg1 mod_hiddens1 pkg_hiddens1 -> do
161 NotFound places2 mb_pkg2 mod_hiddens2 pkg_hiddens2 ->
162 return (NotFound (places1 ++ places2)
163 mb_pkg2 -- snd arg is the package search
164 (mod_hiddens1 ++ mod_hiddens2)
165 (pkg_hiddens1 ++ pkg_hiddens2))
166 _other -> return res2
170 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
171 homeSearchCache hsc_env mod_name do_this = do
172 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
174 Just result -> return result
177 addToFinderCache (hsc_FC hsc_env) mod_name result
179 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
183 findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString
185 findExposedPackageModule hsc_env mod_name mb_pkg
186 -- not found in any package:
187 | null found_exposed = return (NotFound [] Nothing mod_hiddens pkg_hiddens)
188 -- found in just one exposed package:
189 | [(pkg_conf, _)] <- found_exposed
190 = let pkgid = packageConfigId pkg_conf in
191 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
193 = return (FoundMultiple (map (packageConfigId.fst) found_exposed))
195 dflags = hsc_dflags hsc_env
196 found = lookupModuleInAllPackages dflags mod_name
198 for_this_pkg = filter ((`matches` mb_pkg) . fst) found
200 found_exposed = [ (pkg_conf,exposed_mod)
201 | x@(pkg_conf,exposed_mod) <- for_this_pkg,
204 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
206 mod_hiddens = [ packageConfigId pkg_conf
207 | (pkg_conf,False) <- found ]
209 pkg_hiddens = [ packageConfigId pkg_conf
210 | (pkg_conf,_) <- found, not (exposed pkg_conf) ]
212 _pkg_conf `matches` Nothing = True
213 pkg_conf `matches` Just pkg =
214 case packageName pkg_conf of
215 PackageName n -> pkg == mkFastString n
218 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
219 modLocationCache hsc_env mod do_this = do
220 mb_loc <- lookupModLocationCache mlc mod
222 Just loc -> return (Found loc mod)
226 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
230 mlc = hsc_MLC hsc_env
232 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
233 addHomeModuleToFinder hsc_env mod_name loc = do
234 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
235 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
236 addToModLocationCache (hsc_MLC hsc_env) mod loc
239 uncacheModule :: HscEnv -> ModuleName -> IO ()
240 uncacheModule hsc_env mod = do
241 let this_pkg = thisPackage (hsc_dflags hsc_env)
242 removeFromFinderCache (hsc_FC hsc_env) mod
243 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
245 -- -----------------------------------------------------------------------------
246 -- The internal workers
248 -- | Search for a module in the home package only.
249 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
250 findHomeModule hsc_env mod_name =
251 homeSearchCache hsc_env mod_name $
253 dflags = hsc_dflags hsc_env
254 home_path = importPaths dflags
256 mod = mkModule (thisPackage dflags) mod_name
259 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
260 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
263 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
264 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
267 -- In compilation manager modes, we look for source files in the home
268 -- package because we can compile these automatically. In one-shot
269 -- compilation mode we look for .hi and .hi-boot files only.
270 exts | isOneShot (ghcMode dflags) = hi_exts
271 | otherwise = source_exts
274 -- special case for GHC.Prim; we won't find it in the filesystem.
275 -- This is important only when compiling the base package (where GHC.Prim
276 -- is a home module).
278 then return (Found (error "GHC.Prim ModLocation") mod)
281 searchPathExts home_path mod exts
284 -- | Search for a module in external packages only.
285 findPackageModule :: HscEnv -> Module -> IO FindResult
286 findPackageModule hsc_env mod = do
288 dflags = hsc_dflags hsc_env
289 pkg_id = modulePackageId mod
290 pkg_map = pkgIdMap (pkgState dflags)
292 case lookupPackage pkg_map pkg_id of
293 Nothing -> return (NoPackage pkg_id)
294 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
296 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
297 findPackageModule_ hsc_env mod pkg_conf =
298 modLocationCache hsc_env mod $
300 -- special case for GHC.Prim; we won't find it in the filesystem.
302 then return (Found (error "GHC.Prim ModLocation") mod)
306 dflags = hsc_dflags hsc_env
307 tag = buildTag dflags
309 -- hi-suffix for packages depends on the build tag.
310 package_hisuf | null tag = "hi"
311 | otherwise = tag ++ "_hi"
313 mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf
315 import_dirs = importDirs pkg_conf
316 -- we never look for a .hi-boot file in an external package;
317 -- .hi-boot files only make sense for the home package.
320 [one] | MkDepend <- ghcMode dflags -> do
321 -- there's only one place that this .hi file can be, so
322 -- don't bother looking for it.
323 let basename = moduleNameSlashes (moduleName mod)
324 loc <- mk_hi_loc one basename
325 return (Found loc mod)
327 searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)]
329 -- -----------------------------------------------------------------------------
330 -- General path searching
333 :: [FilePath] -- paths to search
334 -> Module -- module name
337 FilePath -> BaseName -> IO ModLocation -- action
342 searchPathExts paths mod exts
343 = do result <- search to_search
345 hPutStrLn stderr (showSDoc $
346 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
347 , nest 2 (vcat (map text paths))
349 Succeeded (loc, p) -> text "Found" <+> ppr loc
350 Failed fs -> text "not found"])
355 basename = moduleNameSlashes (moduleName mod)
357 to_search :: [(FilePath, IO ModLocation)]
358 to_search = [ (file, fn path basename)
361 let base | path == "." = basename
362 | otherwise = path </> basename
366 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod))
368 search ((file, mk_result) : rest) = do
369 b <- doesFileExist file
371 then do { loc <- mk_result; return (Found loc mod) }
374 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
375 -> FilePath -> BaseName -> IO ModLocation
376 mkHomeModLocationSearched dflags mod suff path basename = do
377 mkHomeModLocation2 dflags mod (path </> basename) suff
379 -- -----------------------------------------------------------------------------
380 -- Constructing a home module location
382 -- This is where we construct the ModLocation for a module in the home
383 -- package, for which we have a source file. It is called from three
386 -- (a) Here in the finder, when we are searching for a module to import,
387 -- using the search path (-i option).
389 -- (b) The compilation manager, when constructing the ModLocation for
390 -- a "root" module (a source file named explicitly on the command line
391 -- or in a :load command in GHCi).
393 -- (c) The driver in one-shot mode, when we need to construct a
394 -- ModLocation for a source file named on the command-line.
399 -- The name of the module
402 -- (a): The search path component where the source file was found.
406 -- (a): (moduleNameSlashes mod)
407 -- (b) and (c): The filename of the source file, minus its extension
410 -- The filename extension of the source file (usually "hs" or "lhs").
412 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
413 mkHomeModLocation dflags mod src_filename = do
414 let (basename,extension) = splitExtension src_filename
415 mkHomeModLocation2 dflags mod basename extension
417 mkHomeModLocation2 :: DynFlags
419 -> FilePath -- Of source module, without suffix
422 mkHomeModLocation2 dflags mod src_basename ext = do
423 let mod_basename = moduleNameSlashes mod
425 obj_fn <- mkObjPath dflags src_basename mod_basename
426 hi_fn <- mkHiPath dflags src_basename mod_basename
428 return (ModLocation{ ml_hs_file = Just (src_basename <.> ext),
430 ml_obj_file = obj_fn })
432 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
434 mkHiOnlyModLocation dflags hisuf path basename
435 = do let full_basename = path </> basename
436 obj_fn <- mkObjPath dflags full_basename basename
437 return ModLocation{ ml_hs_file = Nothing,
438 ml_hi_file = full_basename <.> hisuf,
439 -- Remove the .hi-boot suffix from
440 -- hi_file, if it had one. We always
441 -- want the name of the real .hi file
442 -- in the ml_hi_file field.
446 -- | Constructs the filename of a .o file for a given source file.
447 -- Does /not/ check whether the .o file exists
450 -> FilePath -- the filename of the source file, minus the extension
451 -> String -- the module name with dots replaced by slashes
453 mkObjPath dflags basename mod_basename
455 odir = objectDir dflags
456 osuf = objectSuf dflags
458 obj_basename | Just dir <- odir = dir </> mod_basename
459 | otherwise = basename
461 return (obj_basename <.> osuf)
463 -- | Constructs the filename of a .hi file for a given source file.
464 -- Does /not/ check whether the .hi file exists
467 -> FilePath -- the filename of the source file, minus the extension
468 -> String -- the module name with dots replaced by slashes
470 mkHiPath dflags basename mod_basename
475 hi_basename | Just dir <- hidir = dir </> mod_basename
476 | otherwise = basename
478 return (hi_basename <.> hisuf)
481 -- -----------------------------------------------------------------------------
482 -- Filenames of the stub files
484 -- We don't have to store these in ModLocations, because they can be derived
485 -- from other available information, and they're only rarely needed.
491 -> (FilePath,FilePath,FilePath)
493 mkStubPaths dflags mod location
495 stubdir = stubDir dflags
497 mod_basename = moduleNameSlashes mod
498 src_basename = dropExtension $ expectJust "mkStubPaths"
499 (ml_hs_file location)
502 | Just dir <- stubdir = dir </> mod_basename
503 | otherwise = src_basename
505 stub_basename = stub_basename0 ++ "_stub"
507 obj = ml_obj_file location
508 osuf = objectSuf dflags
509 stub_obj_base = dropTail (length osuf + 1) obj ++ "_stub"
510 -- NB. not takeFileName, see #3093
512 (stub_basename <.> "c",
513 stub_basename <.> "h",
514 stub_obj_base <.> objectSuf dflags)
516 -- -----------------------------------------------------------------------------
517 -- findLinkable isn't related to the other stuff in here,
518 -- but there's no other obvious place for it
520 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
521 findObjectLinkableMaybe mod locn
522 = do let obj_fn = ml_obj_file locn
523 maybe_obj_time <- modificationTimeIfExists obj_fn
524 case maybe_obj_time of
525 Nothing -> return Nothing
526 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
528 -- Make an object linkable when we know the object file exists, and we know
529 -- its modification time.
530 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
531 findObjectLinkable mod obj_fn obj_time = do
532 let stub_fn = (dropExtension obj_fn ++ "_stub") <.> "o"
533 stub_exist <- doesFileExist stub_fn
535 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
536 else return (LM obj_time mod [DotO obj_fn])
538 -- -----------------------------------------------------------------------------
541 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
542 cannotFindModule = cantFindErr (sLit "Could not find module")
543 (sLit "Ambiguous module name")
545 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
546 cannotFindInterface = cantFindErr (sLit "Failed to load interface for")
547 (sLit "Ambiguous interface for")
549 cantFindErr :: LitString -> LitString -> DynFlags -> ModuleName -> FindResult
551 cantFindErr _ multiple_found _ mod_name (FoundMultiple pkgs)
552 = hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
553 sep [ptext (sLit "it was found in multiple packages:"),
554 hsep (map (text.packageIdString) pkgs)]
556 cantFindErr cannot_find _ dflags mod_name find_result
557 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
561 = case find_result of
563 -> ptext (sLit "no package matching") <+> quotes (ppr pkg) <+>
564 ptext (sLit "was found")
566 NotFound files mb_pkg mod_hiddens pkg_hiddens
567 | Just pkg <- mb_pkg, pkg /= thisPackage dflags
568 -> not_found_in_package pkg files
570 | null files && null mod_hiddens && null pkg_hiddens
571 -> ptext (sLit "it is not a module in the current program, or in any known package.")
574 -> vcat (map pkg_hidden pkg_hiddens) $$
575 vcat (map mod_hidden mod_hiddens) $$
578 NotFoundInPackage pkg
579 -> ptext (sLit "it is not in package") <+> quotes (ppr pkg)
581 _ -> panic "cantFindErr"
583 build_tag = buildTag dflags
585 not_found_in_package pkg files
588 build = if build_tag == "p" then "profiling"
589 else "\"" ++ build_tag ++ "\""
591 ptext (sLit "Perhaps you haven't installed the ") <> text build <>
592 ptext (sLit " libraries for package ") <> quotes (ppr pkg) <> char '?' $$
596 = ptext (sLit "There are files missing in the ") <> quotes (ppr pkg) <>
597 ptext (sLit " package,") $$
598 ptext (sLit "try running 'ghc-pkg check'.") $$
603 | verbosity dflags < 3 =
604 ptext (sLit "Use -v to see a list of the files searched for.")
606 hang (ptext (sLit "locations searched:")) 2 $ vcat (map text files)
609 ptext (sLit "It is a member of the hidden package") <+> quotes (ppr pkg)
610 <> dot $$ cabal_pkg_hidden_hint pkg
611 cabal_pkg_hidden_hint pkg
612 | dopt Opt_BuildingCabalPackage dflags
613 = case simpleParse (packageIdString pkg) of
615 ptext (sLit "Perhaps you need to add") <+>
616 quotes (text (display (pkgName pid))) <+>
617 ptext (sLit "to the build-depends in your .cabal file.")
622 ptext (sLit "it is a hidden module in the package") <+> quotes (ppr pkg)