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 ref key val = modifyIORef ref $ \c -> addToUFM c key val
84 addToModLocationCache ref key val = modifyIORef ref $ \c -> addToFM c key val
86 removeFromFinderCache ref key = modifyIORef ref $ \c -> delFromUFM c key
87 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
89 lookupFinderCache ref key = do
91 return $! lookupUFM c key
93 lookupModLocationCache ref key = do
95 return $! lookupFM c key
97 -- -----------------------------------------------------------------------------
98 -- The two external entry points
100 -- | Locate a module that was imported by the user. We have the
101 -- module's name, and possibly a package name. Without a package
102 -- name, this function will use the search path and the known exposed
103 -- packages to find the module, if a package is specified then only
104 -- that package is searched for the module.
106 findImportedModule :: HscEnv -> ModuleName -> Maybe PackageId -> IO FindResult
107 findImportedModule hsc_env mod_name mb_pkgid =
109 Nothing -> unqual_import
110 Just pkg | pkg == this_pkg -> home_import
111 | otherwise -> pkg_import pkg
113 dflags = hsc_dflags hsc_env
114 this_pkg = thisPackage dflags
116 home_import = findHomeModule hsc_env mod_name
118 pkg_import pkg = findPackageModule hsc_env (mkModule pkg mod_name)
119 -- ToDo: this isn't quite right, the module we want
120 -- might actually be in another package, but re-exposed
121 -- ToDo: should return NotFoundInPackage if
122 -- the module isn't exposed by the package.
124 unqual_import = home_import
126 findExposedPackageModule hsc_env mod_name
128 -- | Locate a specific 'Module'. The purpose of this function is to
129 -- create a 'ModLocation' for a given 'Module', that is to find out
130 -- where the files associated with this module live. It is used when
131 -- reading the interface for a module mentioned by another interface,
132 -- for example (a "system import").
134 findExactModule :: HscEnv -> Module -> IO FindResult
135 findExactModule hsc_env mod =
136 let dflags = hsc_dflags hsc_env in
137 if modulePackageId mod == thisPackage dflags
138 then findHomeModule hsc_env (moduleName mod)
139 else findPackageModule hsc_env mod
141 -- -----------------------------------------------------------------------------
144 this `orIfNotFound` or_this = do
147 NotFound here _ -> do
150 NotFound or_here pkg -> return (NotFound (here ++ or_here) pkg)
151 _other -> return res2
155 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
156 homeSearchCache hsc_env mod_name do_this = do
157 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
159 Just result -> return result
162 addToFinderCache (hsc_FC hsc_env) mod_name result
164 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
168 findExposedPackageModule :: HscEnv -> ModuleName -> IO FindResult
169 findExposedPackageModule hsc_env mod_name
170 -- not found in any package:
171 | null found = return (NotFound [] Nothing)
172 -- found in just one exposed package:
173 | [(pkg_conf, _)] <- found_exposed
174 = let pkgid = mkPackageId (package pkg_conf) in
175 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
176 -- not found in any exposed package, report how it was hidden:
177 | null found_exposed, ((pkg_conf, exposed_mod):_) <- found
178 = let pkgid = mkPackageId (package pkg_conf) in
180 then return (ModuleHidden pkgid)
181 else return (PackageHidden pkgid)
183 = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
185 dflags = hsc_dflags hsc_env
186 found = lookupModuleInAllPackages dflags mod_name
187 found_exposed = filter is_exposed found
188 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
191 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
192 modLocationCache hsc_env mod do_this = do
193 mb_loc <- lookupModLocationCache mlc mod
195 Just loc -> return (Found loc mod)
199 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
203 mlc = hsc_MLC hsc_env
205 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
206 addHomeModuleToFinder hsc_env mod_name loc = do
207 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
208 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
209 addToModLocationCache (hsc_MLC hsc_env) mod loc
212 uncacheModule :: HscEnv -> ModuleName -> IO ()
213 uncacheModule hsc_env mod = do
214 let this_pkg = thisPackage (hsc_dflags hsc_env)
215 removeFromFinderCache (hsc_FC hsc_env) mod
216 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
218 -- -----------------------------------------------------------------------------
219 -- The internal workers
221 -- | Search for a module in the home package only.
222 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
223 findHomeModule hsc_env mod_name =
224 homeSearchCache hsc_env mod_name $
226 dflags = hsc_dflags hsc_env
227 home_path = importPaths dflags
229 mod = mkModule (thisPackage dflags) mod_name
232 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
233 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
236 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
237 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
240 -- In compilation manager modes, we look for source files in the home
241 -- package because we can compile these automatically. In one-shot
242 -- compilation mode we look for .hi and .hi-boot files only.
243 exts | isOneShot (ghcMode dflags) = hi_exts
244 | otherwise = source_exts
247 -- special case for GHC.Prim; we won't find it in the filesystem.
248 -- This is important only when compiling the base package (where GHC.Prim
249 -- is a home module).
251 then return (Found (error "GHC.Prim ModLocation") mod)
254 searchPathExts home_path mod exts
257 -- | Search for a module in external packages only.
258 findPackageModule :: HscEnv -> Module -> IO FindResult
259 findPackageModule hsc_env mod = do
261 dflags = hsc_dflags hsc_env
262 pkg_id = modulePackageId mod
263 pkg_map = pkgIdMap (pkgState dflags)
265 case lookupPackage pkg_map pkg_id of
266 Nothing -> return (NoPackage pkg_id)
267 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
269 findPackageModule_ hsc_env mod pkg_conf =
270 modLocationCache hsc_env mod $
272 -- special case for GHC.Prim; we won't find it in the filesystem.
274 then return (Found (error "GHC.Prim ModLocation") mod)
278 dflags = hsc_dflags hsc_env
279 tag = buildTag dflags
281 -- hi-suffix for packages depends on the build tag.
282 package_hisuf | null tag = "hi"
283 | otherwise = tag ++ "_hi"
285 [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
288 [ ("hs", mkHiOnlyModLocation dflags package_hisuf)
289 , ("lhs", mkHiOnlyModLocation dflags package_hisuf)
292 -- mkdependHS needs to look for source files in packages too, so
293 -- that we can make dependencies between package before they have
296 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
297 | otherwise = hi_exts
298 -- we never look for a .hi-boot file in an external package;
299 -- .hi-boot files only make sense for the home package.
301 searchPathExts (importDirs pkg_conf) mod exts
303 -- -----------------------------------------------------------------------------
304 -- General path searching
307 :: [FilePath] -- paths to search
308 -> Module -- module name
311 FilePath -> BaseName -> IO ModLocation -- action
316 searchPathExts paths mod exts
317 = do result <- search to_search
319 hPutStrLn stderr (showSDoc $
320 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
321 , nest 2 (vcat (map text paths))
323 Succeeded (loc, p) -> text "Found" <+> ppr loc
324 Failed fs -> text "not found"])
329 basename = dots_to_slashes (moduleNameString (moduleName mod))
331 to_search :: [(FilePath, IO ModLocation)]
332 to_search = [ (file, fn path basename)
335 let base | path == "." = basename
336 | otherwise = path `joinFileName` basename
337 file = base `joinFileExt` ext
340 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
341 search ((file, mk_result) : rest) = do
342 b <- doesFileExist file
344 then do { loc <- mk_result; return (Found loc mod) }
347 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
348 -> FilePath -> BaseName -> IO ModLocation
349 mkHomeModLocationSearched dflags mod suff path basename = do
350 mkHomeModLocation2 dflags mod (path `joinFileName` basename) suff
352 -- -----------------------------------------------------------------------------
353 -- Constructing a home module location
355 -- This is where we construct the ModLocation for a module in the home
356 -- package, for which we have a source file. It is called from three
359 -- (a) Here in the finder, when we are searching for a module to import,
360 -- using the search path (-i option).
362 -- (b) The compilation manager, when constructing the ModLocation for
363 -- a "root" module (a source file named explicitly on the command line
364 -- or in a :load command in GHCi).
366 -- (c) The driver in one-shot mode, when we need to construct a
367 -- ModLocation for a source file named on the command-line.
372 -- The name of the module
375 -- (a): The search path component where the source file was found.
379 -- (a): dots_to_slashes (moduleNameUserString mod)
380 -- (b) and (c): The filename of the source file, minus its extension
383 -- The filename extension of the source file (usually "hs" or "lhs").
385 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
386 mkHomeModLocation dflags mod src_filename = do
387 let (basename,extension) = splitFilename src_filename
388 mkHomeModLocation2 dflags mod basename extension
390 mkHomeModLocation2 :: DynFlags
392 -> FilePath -- Of source module, without suffix
395 mkHomeModLocation2 dflags mod src_basename ext = do
396 let mod_basename = dots_to_slashes (moduleNameString mod)
398 obj_fn <- mkObjPath dflags src_basename mod_basename
399 hi_fn <- mkHiPath dflags src_basename mod_basename
401 return (ModLocation{ ml_hs_file = Just (src_basename `joinFileExt` ext),
403 ml_obj_file = obj_fn })
405 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
407 mkHiOnlyModLocation dflags hisuf path basename
408 = do let full_basename = path `joinFileName` basename
409 obj_fn <- mkObjPath dflags full_basename basename
410 return ModLocation{ ml_hs_file = Nothing,
411 ml_hi_file = full_basename `joinFileExt` hisuf,
412 -- Remove the .hi-boot suffix from
413 -- hi_file, if it had one. We always
414 -- want the name of the real .hi file
415 -- in the ml_hi_file field.
419 -- | Constructs the filename of a .o file for a given source file.
420 -- Does /not/ check whether the .o file exists
423 -> FilePath -- the filename of the source file, minus the extension
424 -> String -- the module name with dots replaced by slashes
426 mkObjPath dflags basename mod_basename
428 odir = objectDir dflags
429 osuf = objectSuf dflags
431 obj_basename | Just dir <- odir = dir `joinFileName` mod_basename
432 | otherwise = basename
434 return (obj_basename `joinFileExt` osuf)
436 -- | Constructs the filename of a .hi file for a given source file.
437 -- Does /not/ check whether the .hi file exists
440 -> FilePath -- the filename of the source file, minus the extension
441 -> String -- the module name with dots replaced by slashes
443 mkHiPath dflags basename mod_basename
448 hi_basename | Just dir <- hidir = dir `joinFileName` mod_basename
449 | otherwise = basename
451 return (hi_basename `joinFileExt` hisuf)
454 -- -----------------------------------------------------------------------------
455 -- Filenames of the stub files
457 -- We don't have to store these in ModLocations, because they can be derived
458 -- from other available information, and they're only rarely needed.
464 -> (FilePath,FilePath)
466 mkStubPaths dflags mod location
468 stubdir = stubDir dflags
470 mod_basename = dots_to_slashes (moduleNameString mod)
471 src_basename = basenameOf (expectJust "mkStubPaths"
472 (ml_hs_file location))
475 | Just dir <- stubdir = dir `joinFileName` mod_basename
476 | otherwise = src_basename
478 stub_basename = stub_basename0 ++ "_stub"
480 (stub_basename `joinFileExt` "c",
481 stub_basename `joinFileExt` "h")
482 -- the _stub.o filename is derived from the ml_obj_file.
484 -- -----------------------------------------------------------------------------
485 -- findLinkable isn't related to the other stuff in here,
486 -- but there's no other obvious place for it
488 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
489 findObjectLinkableMaybe mod locn
490 = do let obj_fn = ml_obj_file locn
491 maybe_obj_time <- modificationTimeIfExists obj_fn
492 case maybe_obj_time of
493 Nothing -> return Nothing
494 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
496 -- Make an object linkable when we know the object file exists, and we know
497 -- its modification time.
498 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
499 findObjectLinkable mod obj_fn obj_time = do
500 let stub_fn = case splitFilename3 obj_fn of
501 (dir, base, ext) -> dir ++ "/" ++ base ++ "_stub.o"
502 stub_exist <- doesFileExist stub_fn
504 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
505 else return (LM obj_time mod [DotO obj_fn])
507 -- -----------------------------------------------------------------------------
510 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
513 -- -----------------------------------------------------------------------------
516 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
517 cannotFindModule = cantFindErr SLIT("Could not find module")
519 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
520 cannotFindInterface = cantFindErr SLIT("Failed to load interface for")
522 cantFindErr cannot_find dflags mod_name (FoundMultiple pkgs)
523 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
524 sep [ptext SLIT("it was found in multiple packages:"),
525 hsep (map (text.packageIdString) pkgs)]
527 cantFindErr cannot_find dflags mod_name find_result
528 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
532 = case find_result of
534 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
535 <+> ptext SLIT("which is hidden")
538 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
542 -> ptext SLIT("no package matching") <+> ppr pkg <+>
543 ptext SLIT("was found")
545 NotFound files mb_pkg
547 -> ptext SLIT("it is not a module in the current program, or in any known package.")
548 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
550 build = if build_tag == "p" then "profiling"
551 else "\"" ++ build_tag ++ "\""
553 ptext SLIT("Perhaps you haven't installed the ") <> text build <>
554 ptext SLIT(" libraries for package ") <> ppr pkg <> char '?' $$
560 NotFoundInPackage pkg
561 -> ptext SLIT("it is not in package") <+> ppr pkg
563 _ -> panic "cantFindErr"
565 build_tag = buildTag dflags
568 | verbosity dflags < 3
569 = ptext SLIT("Use -v to see a list of the files searched for.")
571 = hang (ptext SLIT("locations searched:")) 2 (vcat (map text files))