2 % (c) The University of Glasgow, 2000-2006
4 \section[Finder]{Module Finder}
15 addHomeModuleToFinder,
19 findObjectLinkableMaybe,
26 #include "HsVersions.h"
33 import PrelNames ( gHC_PRIM )
34 import DynFlags ( DynFlags(..), isOneShot, GhcMode(..) )
38 import Maybes ( expectJust )
40 import Data.IORef ( IORef, writeIORef, readIORef, modifyIORef )
42 import System.Directory
45 import System.Time ( ClockTime )
48 type FileExt = String -- Filename extension
49 type BaseName = String -- Basename of file
51 -- -----------------------------------------------------------------------------
54 -- The Finder provides a thin filesystem abstraction to the rest of
55 -- the compiler. For a given module, it can tell you where the
56 -- source, interface, and object files for that module live.
58 -- It does *not* know which particular package a module lives in. Use
59 -- Packages.lookupModuleInAllPackages for that.
61 -- -----------------------------------------------------------------------------
64 -- remove all the home modules from the cache; package modules are
65 -- assumed to not move around during a session.
66 flushFinderCaches :: HscEnv -> IO ()
67 flushFinderCaches hsc_env = do
68 writeIORef fc_ref emptyUFM
69 flushModLocationCache this_pkg mlc_ref
71 this_pkg = thisPackage (hsc_dflags hsc_env)
72 fc_ref = hsc_FC hsc_env
73 mlc_ref = hsc_MLC hsc_env
75 flushModLocationCache :: PackageId -> IORef ModLocationCache -> IO ()
76 flushModLocationCache this_pkg ref = do
78 writeIORef ref $! filterFM is_ext fm
80 where is_ext mod _ | modulePackageId mod /= this_pkg = True
83 addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
84 addToFinderCache ref key val = modifyIORef ref $ \c -> addToUFM c key val
86 addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
87 addToModLocationCache ref key val = modifyIORef ref $ \c -> addToFM c key val
89 removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
90 removeFromFinderCache ref key = modifyIORef ref $ \c -> delFromUFM c key
92 removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
93 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
95 lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
96 lookupFinderCache ref key = do
98 return $! lookupUFM c key
100 lookupModLocationCache :: IORef ModLocationCache -> Module
101 -> IO (Maybe ModLocation)
102 lookupModLocationCache ref key = do
104 return $! lookupFM c key
106 -- -----------------------------------------------------------------------------
107 -- The two external entry points
109 -- | Locate a module that was imported by the user. We have the
110 -- module's name, and possibly a package name. Without a package
111 -- name, this function will use the search path and the known exposed
112 -- packages to find the module, if a package is specified then only
113 -- that package is searched for the module.
115 findImportedModule :: HscEnv -> ModuleName -> Maybe PackageId -> IO FindResult
116 findImportedModule hsc_env mod_name mb_pkgid =
118 Nothing -> unqual_import
119 Just pkg | pkg == this_pkg -> home_import
120 | otherwise -> pkg_import pkg
122 dflags = hsc_dflags hsc_env
123 this_pkg = thisPackage dflags
125 home_import = findHomeModule hsc_env mod_name
127 pkg_import pkg = findPackageModule hsc_env (mkModule pkg mod_name)
128 -- ToDo: this isn't quite right, the module we want
129 -- might actually be in another package, but re-exposed
130 -- ToDo: should return NotFoundInPackage if
131 -- the module isn't exposed by the package.
133 unqual_import = home_import
135 findExposedPackageModule hsc_env mod_name
137 -- | Locate a specific 'Module'. The purpose of this function is to
138 -- create a 'ModLocation' for a given 'Module', that is to find out
139 -- where the files associated with this module live. It is used when
140 -- reading the interface for a module mentioned by another interface,
141 -- for example (a "system import").
143 findExactModule :: HscEnv -> Module -> IO FindResult
144 findExactModule hsc_env mod =
145 let dflags = hsc_dflags hsc_env in
146 if modulePackageId mod == thisPackage dflags
147 then findHomeModule hsc_env (moduleName mod)
148 else findPackageModule hsc_env mod
150 -- -----------------------------------------------------------------------------
153 orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
154 this `orIfNotFound` or_this = do
157 NotFound here _ -> do
160 NotFound or_here pkg -> return (NotFound (here ++ or_here) pkg)
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 -> IO FindResult
179 findExposedPackageModule hsc_env mod_name
180 -- not found in any package:
181 | null found = return (NotFound [] Nothing)
182 -- found in just one exposed package:
183 | [(pkg_conf, _)] <- found_exposed
184 = let pkgid = mkPackageId (package pkg_conf) in
185 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
186 -- not found in any exposed package, report how it was hidden:
187 | null found_exposed, ((pkg_conf, exposed_mod):_) <- found
188 = let pkgid = mkPackageId (package pkg_conf) in
190 then return (ModuleHidden pkgid)
191 else return (PackageHidden pkgid)
193 = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
195 dflags = hsc_dflags hsc_env
196 found = lookupModuleInAllPackages dflags mod_name
197 found_exposed = filter is_exposed found
198 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
201 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
202 modLocationCache hsc_env mod do_this = do
203 mb_loc <- lookupModLocationCache mlc mod
205 Just loc -> return (Found loc mod)
209 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
213 mlc = hsc_MLC hsc_env
215 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
216 addHomeModuleToFinder hsc_env mod_name loc = do
217 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
218 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
219 addToModLocationCache (hsc_MLC hsc_env) mod loc
222 uncacheModule :: HscEnv -> ModuleName -> IO ()
223 uncacheModule hsc_env mod = do
224 let this_pkg = thisPackage (hsc_dflags hsc_env)
225 removeFromFinderCache (hsc_FC hsc_env) mod
226 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
228 -- -----------------------------------------------------------------------------
229 -- The internal workers
231 -- | Search for a module in the home package only.
232 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
233 findHomeModule hsc_env mod_name =
234 homeSearchCache hsc_env mod_name $
236 dflags = hsc_dflags hsc_env
237 home_path = importPaths dflags
239 mod = mkModule (thisPackage dflags) mod_name
242 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
243 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
246 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
247 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
250 -- In compilation manager modes, we look for source files in the home
251 -- package because we can compile these automatically. In one-shot
252 -- compilation mode we look for .hi and .hi-boot files only.
253 exts | isOneShot (ghcMode dflags) = hi_exts
254 | otherwise = source_exts
257 -- special case for GHC.Prim; we won't find it in the filesystem.
258 -- This is important only when compiling the base package (where GHC.Prim
259 -- is a home module).
261 then return (Found (error "GHC.Prim ModLocation") mod)
264 searchPathExts home_path mod exts
267 -- | Search for a module in external packages only.
268 findPackageModule :: HscEnv -> Module -> IO FindResult
269 findPackageModule hsc_env mod = do
271 dflags = hsc_dflags hsc_env
272 pkg_id = modulePackageId mod
273 pkg_map = pkgIdMap (pkgState dflags)
275 case lookupPackage pkg_map pkg_id of
276 Nothing -> return (NoPackage pkg_id)
277 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
279 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
280 findPackageModule_ hsc_env mod pkg_conf =
281 modLocationCache hsc_env mod $
283 -- special case for GHC.Prim; we won't find it in the filesystem.
285 then return (Found (error "GHC.Prim ModLocation") mod)
289 dflags = hsc_dflags hsc_env
290 tag = buildTag dflags
292 -- hi-suffix for packages depends on the build tag.
293 package_hisuf | null tag = "hi"
294 | otherwise = tag ++ "_hi"
296 [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
299 [ ("hs", mkHiOnlyModLocation dflags package_hisuf)
300 , ("lhs", mkHiOnlyModLocation dflags package_hisuf)
303 -- mkdependHS needs to look for source files in packages too, so
304 -- that we can make dependencies between package before they have
307 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
308 | otherwise = hi_exts
309 -- we never look for a .hi-boot file in an external package;
310 -- .hi-boot files only make sense for the home package.
312 searchPathExts (importDirs pkg_conf) mod exts
314 -- -----------------------------------------------------------------------------
315 -- General path searching
318 :: [FilePath] -- paths to search
319 -> Module -- module name
322 FilePath -> BaseName -> IO ModLocation -- action
327 searchPathExts paths mod exts
328 = do result <- search to_search
330 hPutStrLn stderr (showSDoc $
331 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
332 , nest 2 (vcat (map text paths))
334 Succeeded (loc, p) -> text "Found" <+> ppr loc
335 Failed fs -> text "not found"])
340 basename = dots_to_slashes (moduleNameString (moduleName mod))
342 to_search :: [(FilePath, IO ModLocation)]
343 to_search = [ (file, fn path basename)
346 let base | path == "." = basename
347 | otherwise = path `joinFileName` basename
348 file = base `joinFileExt` ext
351 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
352 search ((file, mk_result) : rest) = do
353 b <- doesFileExist file
355 then do { loc <- mk_result; return (Found loc mod) }
358 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
359 -> FilePath -> BaseName -> IO ModLocation
360 mkHomeModLocationSearched dflags mod suff path basename = do
361 mkHomeModLocation2 dflags mod (path `joinFileName` basename) suff
363 -- -----------------------------------------------------------------------------
364 -- Constructing a home module location
366 -- This is where we construct the ModLocation for a module in the home
367 -- package, for which we have a source file. It is called from three
370 -- (a) Here in the finder, when we are searching for a module to import,
371 -- using the search path (-i option).
373 -- (b) The compilation manager, when constructing the ModLocation for
374 -- a "root" module (a source file named explicitly on the command line
375 -- or in a :load command in GHCi).
377 -- (c) The driver in one-shot mode, when we need to construct a
378 -- ModLocation for a source file named on the command-line.
383 -- The name of the module
386 -- (a): The search path component where the source file was found.
390 -- (a): dots_to_slashes (moduleNameUserString mod)
391 -- (b) and (c): The filename of the source file, minus its extension
394 -- The filename extension of the source file (usually "hs" or "lhs").
396 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
397 mkHomeModLocation dflags mod src_filename = do
398 let (basename,extension) = splitFilename src_filename
399 mkHomeModLocation2 dflags mod basename extension
401 mkHomeModLocation2 :: DynFlags
403 -> FilePath -- Of source module, without suffix
406 mkHomeModLocation2 dflags mod src_basename ext = do
407 let mod_basename = dots_to_slashes (moduleNameString mod)
409 obj_fn <- mkObjPath dflags src_basename mod_basename
410 hi_fn <- mkHiPath dflags src_basename mod_basename
412 return (ModLocation{ ml_hs_file = Just (src_basename `joinFileExt` ext),
414 ml_obj_file = obj_fn })
416 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
418 mkHiOnlyModLocation dflags hisuf path basename
419 = do let full_basename = path `joinFileName` basename
420 obj_fn <- mkObjPath dflags full_basename basename
421 return ModLocation{ ml_hs_file = Nothing,
422 ml_hi_file = full_basename `joinFileExt` hisuf,
423 -- Remove the .hi-boot suffix from
424 -- hi_file, if it had one. We always
425 -- want the name of the real .hi file
426 -- in the ml_hi_file field.
430 -- | Constructs the filename of a .o file for a given source file.
431 -- Does /not/ check whether the .o file exists
434 -> FilePath -- the filename of the source file, minus the extension
435 -> String -- the module name with dots replaced by slashes
437 mkObjPath dflags basename mod_basename
439 odir = objectDir dflags
440 osuf = objectSuf dflags
442 obj_basename | Just dir <- odir = dir `joinFileName` mod_basename
443 | otherwise = basename
445 return (obj_basename `joinFileExt` osuf)
447 -- | Constructs the filename of a .hi file for a given source file.
448 -- Does /not/ check whether the .hi file exists
451 -> FilePath -- the filename of the source file, minus the extension
452 -> String -- the module name with dots replaced by slashes
454 mkHiPath dflags basename mod_basename
459 hi_basename | Just dir <- hidir = dir `joinFileName` mod_basename
460 | otherwise = basename
462 return (hi_basename `joinFileExt` hisuf)
465 -- -----------------------------------------------------------------------------
466 -- Filenames of the stub files
468 -- We don't have to store these in ModLocations, because they can be derived
469 -- from other available information, and they're only rarely needed.
475 -> (FilePath,FilePath,FilePath)
477 mkStubPaths dflags mod location
479 stubdir = stubDir dflags
481 mod_basename = dots_to_slashes (moduleNameString mod)
482 src_basename = basenameOf (expectJust "mkStubPaths"
483 (ml_hs_file location))
486 | Just dir <- stubdir = dir `joinFileName` mod_basename
487 | otherwise = src_basename
489 stub_basename = stub_basename0 ++ "_stub"
491 -- this is the filename we're going to use when
492 -- #including the stub_h file from the .hc file.
493 -- Without -stubdir, we just #include the basename
494 -- (eg. for a module A.B, we #include "B_stub.h"),
495 -- relying on the fact that we add an implicit -I flag
496 -- for the directory in which the source file resides
497 -- (see DriverPipeline.hs). With -stubdir, we
498 -- #include "A/B.h", assuming that the user has added
499 -- -I<dir> along with -stubdir <dir>.
501 | Just _ <- stubdir = mod_basename
502 | otherwise = filenameOf src_basename
504 (stub_basename `joinFileExt` "c",
505 stub_basename `joinFileExt` "h",
506 (include_basename ++ "_stub") `joinFileExt` "h")
507 -- the _stub.o filename is derived from the ml_obj_file.
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 = case splitFilename3 obj_fn of
526 (dir, base, _ext) -> dir ++ "/" ++ base ++ "_stub.o"
527 stub_exist <- doesFileExist stub_fn
529 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
530 else return (LM obj_time mod [DotO obj_fn])
532 -- -----------------------------------------------------------------------------
535 dots_to_slashes :: String -> String
536 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
538 -- -----------------------------------------------------------------------------
541 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
542 cannotFindModule = cantFindErr SLIT("Could not find module")
544 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
545 cannotFindInterface = cantFindErr SLIT("Failed to load interface for")
547 cantFindErr :: LitString -> DynFlags -> ModuleName -> FindResult -> SDoc
548 cantFindErr cannot_find _dflags mod_name (FoundMultiple pkgs)
549 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
550 sep [ptext SLIT("it was found in multiple packages:"),
551 hsep (map (text.packageIdString) pkgs)]
553 cantFindErr cannot_find dflags mod_name find_result
554 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
558 = case find_result of
560 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
561 <+> ptext SLIT("which is hidden")
564 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
568 -> ptext SLIT("no package matching") <+> ppr pkg <+>
569 ptext SLIT("was found")
571 NotFound files mb_pkg
573 -> ptext SLIT("it is not a module in the current program, or in any known package.")
574 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
576 build = if build_tag == "p" then "profiling"
577 else "\"" ++ build_tag ++ "\""
579 ptext SLIT("Perhaps you haven't installed the ") <> text build <>
580 ptext SLIT(" libraries for package ") <> ppr pkg <> char '?' $$
586 NotFoundInPackage pkg
587 -> ptext SLIT("it is not in package") <+> ppr pkg
589 _ -> panic "cantFindErr"
591 build_tag = buildTag dflags
594 | verbosity dflags < 3
595 = ptext SLIT("Use -v to see a list of the files searched for.")
597 = hang (ptext SLIT("locations searched:")) 2 (vcat (map text files))