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 )
43 import System.Directory
44 import System.FilePath
46 import System.Time ( ClockTime )
49 type FileExt = String -- Filename extension
50 type BaseName = String -- Basename of file
52 -- -----------------------------------------------------------------------------
55 -- The Finder provides a thin filesystem abstraction to the rest of
56 -- the compiler. For a given module, it can tell you where the
57 -- source, interface, and object files for that module live.
59 -- It does *not* know which particular package a module lives in. Use
60 -- Packages.lookupModuleInAllPackages for that.
62 -- -----------------------------------------------------------------------------
65 -- remove all the home modules from the cache; package modules are
66 -- assumed to not move around during a session.
67 flushFinderCaches :: HscEnv -> IO ()
68 flushFinderCaches hsc_env = do
69 writeIORef fc_ref emptyUFM
70 flushModLocationCache this_pkg mlc_ref
72 this_pkg = thisPackage (hsc_dflags hsc_env)
73 fc_ref = hsc_FC hsc_env
74 mlc_ref = hsc_MLC hsc_env
76 flushModLocationCache :: PackageId -> IORef ModLocationCache -> IO ()
77 flushModLocationCache this_pkg ref = do
79 writeIORef ref $! filterFM is_ext fm
81 where is_ext mod _ | modulePackageId mod /= this_pkg = True
84 addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
85 addToFinderCache ref key val = modifyIORef ref $ \c -> addToUFM c key val
87 addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
88 addToModLocationCache ref key val = modifyIORef ref $ \c -> addToFM c key val
90 removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
91 removeFromFinderCache ref key = modifyIORef ref $ \c -> delFromUFM c key
93 removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
94 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
96 lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
97 lookupFinderCache ref key = do
99 return $! lookupUFM c key
101 lookupModLocationCache :: IORef ModLocationCache -> Module
102 -> IO (Maybe ModLocation)
103 lookupModLocationCache ref key = do
105 return $! lookupFM c key
107 -- -----------------------------------------------------------------------------
108 -- The two external entry points
110 -- | Locate a module that was imported by the user. We have the
111 -- module's name, and possibly a package name. Without a package
112 -- name, this function will use the search path and the known exposed
113 -- packages to find the module, if a package is specified then only
114 -- that package is searched for the module.
116 findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
117 findImportedModule hsc_env mod_name mb_pkg =
119 Nothing -> unqual_import
120 Just pkg | pkg == fsLit "this" -> home_import -- "this" is special
121 | otherwise -> pkg_import
123 home_import = findHomeModule hsc_env mod_name
125 pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg
127 unqual_import = home_import
129 findExposedPackageModule hsc_env mod_name Nothing
131 -- | Locate a specific 'Module'. The purpose of this function is to
132 -- create a 'ModLocation' for a given 'Module', that is to find out
133 -- where the files associated with this module live. It is used when
134 -- reading the interface for a module mentioned by another interface,
135 -- for example (a "system import").
137 findExactModule :: HscEnv -> Module -> IO FindResult
138 findExactModule hsc_env mod =
139 let dflags = hsc_dflags hsc_env in
140 if modulePackageId mod == thisPackage dflags
141 then findHomeModule hsc_env (moduleName mod)
142 else findPackageModule hsc_env mod
144 -- -----------------------------------------------------------------------------
147 orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
148 this `orIfNotFound` or_this = do
151 NotFound places1 _mb_pkg1 mod_hiddens1 pkg_hiddens1 -> do
154 NotFound places2 mb_pkg2 mod_hiddens2 pkg_hiddens2 ->
155 return (NotFound (places1 ++ places2)
156 mb_pkg2 -- snd arg is the package search
157 (mod_hiddens1 ++ mod_hiddens2)
158 (pkg_hiddens1 ++ pkg_hiddens2))
159 _other -> return res2
163 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
164 homeSearchCache hsc_env mod_name do_this = do
165 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
167 Just result -> return result
170 addToFinderCache (hsc_FC hsc_env) mod_name result
172 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
176 findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString
178 findExposedPackageModule hsc_env mod_name mb_pkg
179 -- not found in any package:
180 | null found_exposed = return (NotFound [] Nothing mod_hiddens pkg_hiddens)
181 -- found in just one exposed package:
182 | [(pkg_conf, _)] <- found_exposed
183 = let pkgid = packageConfigId pkg_conf in
184 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
186 = return (FoundMultiple (map (packageConfigId.fst) found_exposed))
188 dflags = hsc_dflags hsc_env
189 found = lookupModuleInAllPackages dflags mod_name
191 for_this_pkg = filter ((`matches` mb_pkg) . fst) found
193 found_exposed = [ (pkg_conf,exposed_mod)
194 | x@(pkg_conf,exposed_mod) <- for_this_pkg,
197 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
199 mod_hiddens = [ packageConfigId pkg_conf
200 | (pkg_conf,False) <- found ]
202 pkg_hiddens = [ packageConfigId pkg_conf
203 | (pkg_conf,_) <- found, not (exposed pkg_conf) ]
205 _pkg_conf `matches` Nothing = True
206 pkg_conf `matches` Just pkg =
207 case packageName pkg_conf of
208 PackageName n -> pkg == mkFastString n
211 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
212 modLocationCache hsc_env mod do_this = do
213 mb_loc <- lookupModLocationCache mlc mod
215 Just loc -> return (Found loc mod)
219 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
223 mlc = hsc_MLC hsc_env
225 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
226 addHomeModuleToFinder hsc_env mod_name loc = do
227 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
228 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
229 addToModLocationCache (hsc_MLC hsc_env) mod loc
232 uncacheModule :: HscEnv -> ModuleName -> IO ()
233 uncacheModule hsc_env mod = do
234 let this_pkg = thisPackage (hsc_dflags hsc_env)
235 removeFromFinderCache (hsc_FC hsc_env) mod
236 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
238 -- -----------------------------------------------------------------------------
239 -- The internal workers
241 -- | Search for a module in the home package only.
242 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
243 findHomeModule hsc_env mod_name =
244 homeSearchCache hsc_env mod_name $
246 dflags = hsc_dflags hsc_env
247 home_path = importPaths dflags
249 mod = mkModule (thisPackage dflags) mod_name
252 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
253 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
256 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
257 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
260 -- In compilation manager modes, we look for source files in the home
261 -- package because we can compile these automatically. In one-shot
262 -- compilation mode we look for .hi and .hi-boot files only.
263 exts | isOneShot (ghcMode dflags) = hi_exts
264 | otherwise = source_exts
267 -- special case for GHC.Prim; we won't find it in the filesystem.
268 -- This is important only when compiling the base package (where GHC.Prim
269 -- is a home module).
271 then return (Found (error "GHC.Prim ModLocation") mod)
274 searchPathExts home_path mod exts
277 -- | Search for a module in external packages only.
278 findPackageModule :: HscEnv -> Module -> IO FindResult
279 findPackageModule hsc_env mod = do
281 dflags = hsc_dflags hsc_env
282 pkg_id = modulePackageId mod
283 pkg_map = pkgIdMap (pkgState dflags)
285 case lookupPackage pkg_map pkg_id of
286 Nothing -> return (NoPackage pkg_id)
287 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
289 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
290 findPackageModule_ hsc_env mod pkg_conf =
291 modLocationCache hsc_env mod $
293 -- special case for GHC.Prim; we won't find it in the filesystem.
295 then return (Found (error "GHC.Prim ModLocation") mod)
299 dflags = hsc_dflags hsc_env
300 tag = buildTag dflags
302 -- hi-suffix for packages depends on the build tag.
303 package_hisuf | null tag = "hi"
304 | otherwise = tag ++ "_hi"
306 mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf
308 import_dirs = importDirs pkg_conf
309 -- we never look for a .hi-boot file in an external package;
310 -- .hi-boot files only make sense for the home package.
313 [one] | MkDepend <- ghcMode dflags -> do
314 -- there's only one place that this .hi file can be, so
315 -- don't bother looking for it.
316 let basename = moduleNameSlashes (moduleName mod)
317 loc <- mk_hi_loc one basename
318 return (Found loc mod)
320 searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)]
322 -- -----------------------------------------------------------------------------
323 -- General path searching
326 :: [FilePath] -- paths to search
327 -> Module -- module name
330 FilePath -> BaseName -> IO ModLocation -- action
335 searchPathExts paths mod exts
336 = do result <- search to_search
338 hPutStrLn stderr (showSDoc $
339 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
340 , nest 2 (vcat (map text paths))
342 Succeeded (loc, p) -> text "Found" <+> ppr loc
343 Failed fs -> text "not found"])
348 basename = moduleNameSlashes (moduleName mod)
350 to_search :: [(FilePath, IO ModLocation)]
351 to_search = [ (file, fn path basename)
354 let base | path == "." = basename
355 | otherwise = path </> basename
359 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod))
361 search ((file, mk_result) : rest) = do
362 b <- doesFileExist file
364 then do { loc <- mk_result; return (Found loc mod) }
367 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
368 -> FilePath -> BaseName -> IO ModLocation
369 mkHomeModLocationSearched dflags mod suff path basename = do
370 mkHomeModLocation2 dflags mod (path </> basename) suff
372 -- -----------------------------------------------------------------------------
373 -- Constructing a home module location
375 -- This is where we construct the ModLocation for a module in the home
376 -- package, for which we have a source file. It is called from three
379 -- (a) Here in the finder, when we are searching for a module to import,
380 -- using the search path (-i option).
382 -- (b) The compilation manager, when constructing the ModLocation for
383 -- a "root" module (a source file named explicitly on the command line
384 -- or in a :load command in GHCi).
386 -- (c) The driver in one-shot mode, when we need to construct a
387 -- ModLocation for a source file named on the command-line.
392 -- The name of the module
395 -- (a): The search path component where the source file was found.
399 -- (a): (moduleNameSlashes mod)
400 -- (b) and (c): The filename of the source file, minus its extension
403 -- The filename extension of the source file (usually "hs" or "lhs").
405 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
406 mkHomeModLocation dflags mod src_filename = do
407 let (basename,extension) = splitExtension src_filename
408 mkHomeModLocation2 dflags mod basename extension
410 mkHomeModLocation2 :: DynFlags
412 -> FilePath -- Of source module, without suffix
415 mkHomeModLocation2 dflags mod src_basename ext = do
416 let mod_basename = moduleNameSlashes mod
418 obj_fn <- mkObjPath dflags src_basename mod_basename
419 hi_fn <- mkHiPath dflags src_basename mod_basename
421 return (ModLocation{ ml_hs_file = Just (src_basename <.> ext),
423 ml_obj_file = obj_fn })
425 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
427 mkHiOnlyModLocation dflags hisuf path basename
428 = do let full_basename = path </> basename
429 obj_fn <- mkObjPath dflags full_basename basename
430 return ModLocation{ ml_hs_file = Nothing,
431 ml_hi_file = full_basename <.> hisuf,
432 -- Remove the .hi-boot suffix from
433 -- hi_file, if it had one. We always
434 -- want the name of the real .hi file
435 -- in the ml_hi_file field.
439 -- | Constructs the filename of a .o file for a given source file.
440 -- Does /not/ check whether the .o file exists
443 -> FilePath -- the filename of the source file, minus the extension
444 -> String -- the module name with dots replaced by slashes
446 mkObjPath dflags basename mod_basename
448 odir = objectDir dflags
449 osuf = objectSuf dflags
451 obj_basename | Just dir <- odir = dir </> mod_basename
452 | otherwise = basename
454 return (obj_basename <.> osuf)
456 -- | Constructs the filename of a .hi file for a given source file.
457 -- Does /not/ check whether the .hi file exists
460 -> FilePath -- the filename of the source file, minus the extension
461 -> String -- the module name with dots replaced by slashes
463 mkHiPath dflags basename mod_basename
468 hi_basename | Just dir <- hidir = dir </> mod_basename
469 | otherwise = basename
471 return (hi_basename <.> hisuf)
474 -- -----------------------------------------------------------------------------
475 -- Filenames of the stub files
477 -- We don't have to store these in ModLocations, because they can be derived
478 -- from other available information, and they're only rarely needed.
484 -> (FilePath,FilePath,FilePath)
486 mkStubPaths dflags mod location
488 stubdir = stubDir dflags
490 mod_basename = moduleNameSlashes mod
491 src_basename = dropExtension $ expectJust "mkStubPaths"
492 (ml_hs_file location)
495 | Just dir <- stubdir = dir </> mod_basename
496 | otherwise = src_basename
498 stub_basename = stub_basename0 ++ "_stub"
500 obj = ml_obj_file location
501 osuf = objectSuf dflags
502 stub_obj_base = dropTail (length osuf + 1) obj ++ "_stub"
503 -- NB. not takeFileName, see #3093
505 (stub_basename <.> "c",
506 stub_basename <.> "h",
507 stub_obj_base <.> objectSuf dflags)
509 -- -----------------------------------------------------------------------------
510 -- findLinkable isn't related to the other stuff in here,
511 -- but there's no other obvious place for it
513 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
514 findObjectLinkableMaybe mod locn
515 = do let obj_fn = ml_obj_file locn
516 maybe_obj_time <- modificationTimeIfExists obj_fn
517 case maybe_obj_time of
518 Nothing -> return Nothing
519 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
521 -- Make an object linkable when we know the object file exists, and we know
522 -- its modification time.
523 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
524 findObjectLinkable mod obj_fn obj_time = do
525 let stub_fn = (dropExtension obj_fn ++ "_stub") <.> "o"
526 stub_exist <- doesFileExist stub_fn
528 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
529 else return (LM obj_time mod [DotO obj_fn])
531 -- -----------------------------------------------------------------------------
534 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
535 cannotFindModule = cantFindErr (sLit "Could not find module")
536 (sLit "Ambiguous module name")
538 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
539 cannotFindInterface = cantFindErr (sLit "Failed to load interface for")
540 (sLit "Ambiguous interface for")
542 cantFindErr :: LitString -> LitString -> DynFlags -> ModuleName -> FindResult
544 cantFindErr _ multiple_found _ mod_name (FoundMultiple pkgs)
545 = hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
546 sep [ptext (sLit "it was found in multiple packages:"),
547 hsep (map (text.packageIdString) pkgs)]
549 cantFindErr cannot_find _ dflags mod_name find_result
550 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
554 = case find_result of
556 -> ptext (sLit "no package matching") <+> quotes (ppr pkg) <+>
557 ptext (sLit "was found")
559 NotFound files mb_pkg mod_hiddens pkg_hiddens
560 | Just pkg <- mb_pkg, pkg /= thisPackage dflags
561 -> not_found_in_package pkg files
563 | null files && null mod_hiddens && null pkg_hiddens
564 -> ptext (sLit "it is not a module in the current program, or in any known package.")
567 -> vcat (map pkg_hidden pkg_hiddens) $$
568 vcat (map mod_hidden mod_hiddens) $$
571 NotFoundInPackage pkg
572 -> ptext (sLit "it is not in package") <+> quotes (ppr pkg)
574 _ -> panic "cantFindErr"
576 build_tag = buildTag dflags
578 not_found_in_package pkg files
581 build = if build_tag == "p" then "profiling"
582 else "\"" ++ build_tag ++ "\""
584 ptext (sLit "Perhaps you haven't installed the ") <> text build <>
585 ptext (sLit " libraries for package ") <> quotes (ppr pkg) <> char '?' $$
589 = ptext (sLit "There are files missing in the ") <> quotes (ppr pkg) <>
590 ptext (sLit " package,") $$
591 ptext (sLit "try running 'ghc-pkg check'.") $$
596 | verbosity dflags < 3 =
597 ptext (sLit "Use -v to see a list of the files searched for.")
599 hang (ptext (sLit "locations searched:")) 2 $ vcat (map text files)
602 ptext (sLit "it is a member of the hidden package") <+> quotes (ppr pkg)
605 ptext (sLit "it is a hidden module in the package") <+> quotes (ppr pkg)