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
246 searchPathExts home_path mod exts
249 -- | Search for a module in external packages only.
250 findPackageModule :: HscEnv -> Module -> IO FindResult
251 findPackageModule hsc_env mod = do
253 dflags = hsc_dflags hsc_env
254 pkg_id = modulePackageId mod
255 pkg_map = pkgIdMap (pkgState dflags)
257 case lookupPackage pkg_map pkg_id of
258 Nothing -> return (NoPackage pkg_id)
259 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
261 findPackageModule_ hsc_env mod pkg_conf =
262 modLocationCache hsc_env mod $
264 -- special case for GHC.Prim; we won't find it in the filesystem.
266 then return (Found (error "GHC.Prim ModLocation") mod)
270 dflags = hsc_dflags hsc_env
271 tag = buildTag dflags
273 -- hi-suffix for packages depends on the build tag.
274 package_hisuf | null tag = "hi"
275 | otherwise = tag ++ "_hi"
277 [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
280 [ ("hs", mkHiOnlyModLocation dflags package_hisuf)
281 , ("lhs", mkHiOnlyModLocation dflags package_hisuf)
284 -- mkdependHS needs to look for source files in packages too, so
285 -- that we can make dependencies between package before they have
288 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
289 | otherwise = hi_exts
290 -- we never look for a .hi-boot file in an external package;
291 -- .hi-boot files only make sense for the home package.
293 searchPathExts (importDirs pkg_conf) mod exts
295 -- -----------------------------------------------------------------------------
296 -- General path searching
299 :: [FilePath] -- paths to search
300 -> Module -- module name
303 FilePath -> BaseName -> IO ModLocation -- action
308 searchPathExts paths mod exts
309 = do result <- search to_search
311 hPutStrLn stderr (showSDoc $
312 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
313 , nest 2 (vcat (map text paths))
315 Succeeded (loc, p) -> text "Found" <+> ppr loc
316 Failed fs -> text "not found"])
321 basename = dots_to_slashes (moduleNameString (moduleName mod))
323 to_search :: [(FilePath, IO ModLocation)]
324 to_search = [ (file, fn path basename)
327 let base | path == "." = basename
328 | otherwise = path `joinFileName` basename
329 file = base `joinFileExt` ext
332 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
333 search ((file, mk_result) : rest) = do
334 b <- doesFileExist file
336 then do { loc <- mk_result; return (Found loc mod) }
339 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
340 -> FilePath -> BaseName -> IO ModLocation
341 mkHomeModLocationSearched dflags mod suff path basename = do
342 mkHomeModLocation2 dflags mod (path `joinFileName` basename) suff
344 -- -----------------------------------------------------------------------------
345 -- Constructing a home module location
347 -- This is where we construct the ModLocation for a module in the home
348 -- package, for which we have a source file. It is called from three
351 -- (a) Here in the finder, when we are searching for a module to import,
352 -- using the search path (-i option).
354 -- (b) The compilation manager, when constructing the ModLocation for
355 -- a "root" module (a source file named explicitly on the command line
356 -- or in a :load command in GHCi).
358 -- (c) The driver in one-shot mode, when we need to construct a
359 -- ModLocation for a source file named on the command-line.
364 -- The name of the module
367 -- (a): The search path component where the source file was found.
371 -- (a): dots_to_slashes (moduleNameUserString mod)
372 -- (b) and (c): The filename of the source file, minus its extension
375 -- The filename extension of the source file (usually "hs" or "lhs").
377 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
378 mkHomeModLocation dflags mod src_filename = do
379 let (basename,extension) = splitFilename src_filename
380 mkHomeModLocation2 dflags mod basename extension
382 mkHomeModLocation2 :: DynFlags
384 -> FilePath -- Of source module, without suffix
387 mkHomeModLocation2 dflags mod src_basename ext = do
388 let mod_basename = dots_to_slashes (moduleNameString mod)
390 obj_fn <- mkObjPath dflags src_basename mod_basename
391 hi_fn <- mkHiPath dflags src_basename mod_basename
393 return (ModLocation{ ml_hs_file = Just (src_basename `joinFileExt` ext),
395 ml_obj_file = obj_fn })
397 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
399 mkHiOnlyModLocation dflags hisuf path basename
400 = do let full_basename = path `joinFileName` basename
401 obj_fn <- mkObjPath dflags full_basename basename
402 return ModLocation{ ml_hs_file = Nothing,
403 ml_hi_file = full_basename `joinFileExt` hisuf,
404 -- Remove the .hi-boot suffix from
405 -- hi_file, if it had one. We always
406 -- want the name of the real .hi file
407 -- in the ml_hi_file field.
411 -- | Constructs the filename of a .o file for a given source file.
412 -- Does /not/ check whether the .o file exists
415 -> FilePath -- the filename of the source file, minus the extension
416 -> String -- the module name with dots replaced by slashes
418 mkObjPath dflags basename mod_basename
420 odir = objectDir dflags
421 osuf = objectSuf dflags
423 obj_basename | Just dir <- odir = dir `joinFileName` mod_basename
424 | otherwise = basename
426 return (obj_basename `joinFileExt` osuf)
428 -- | Constructs the filename of a .hi file for a given source file.
429 -- Does /not/ check whether the .hi file exists
432 -> FilePath -- the filename of the source file, minus the extension
433 -> String -- the module name with dots replaced by slashes
435 mkHiPath dflags basename mod_basename
440 hi_basename | Just dir <- hidir = dir `joinFileName` mod_basename
441 | otherwise = basename
443 return (hi_basename `joinFileExt` hisuf)
446 -- -----------------------------------------------------------------------------
447 -- Filenames of the stub files
449 -- We don't have to store these in ModLocations, because they can be derived
450 -- from other available information, and they're only rarely needed.
456 -> (FilePath,FilePath)
458 mkStubPaths dflags mod location
460 stubdir = stubDir dflags
462 mod_basename = dots_to_slashes (moduleNameString mod)
463 src_basename = basenameOf (expectJust "mkStubPaths"
464 (ml_hs_file location))
467 | Just dir <- stubdir = dir `joinFileName` mod_basename
468 | otherwise = src_basename
470 stub_basename = stub_basename0 ++ "_stub"
472 (stub_basename `joinFileExt` "c",
473 stub_basename `joinFileExt` "h")
474 -- the _stub.o filename is derived from the ml_obj_file.
476 -- -----------------------------------------------------------------------------
477 -- findLinkable isn't related to the other stuff in here,
478 -- but there's no other obvious place for it
480 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
481 findObjectLinkableMaybe mod locn
482 = do let obj_fn = ml_obj_file locn
483 maybe_obj_time <- modificationTimeIfExists obj_fn
484 case maybe_obj_time of
485 Nothing -> return Nothing
486 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
488 -- Make an object linkable when we know the object file exists, and we know
489 -- its modification time.
490 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
491 findObjectLinkable mod obj_fn obj_time = do
492 let stub_fn = case splitFilename3 obj_fn of
493 (dir, base, ext) -> dir ++ "/" ++ base ++ "_stub.o"
494 stub_exist <- doesFileExist stub_fn
496 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
497 else return (LM obj_time mod [DotO obj_fn])
499 -- -----------------------------------------------------------------------------
502 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
505 -- -----------------------------------------------------------------------------
508 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
509 cannotFindModule = cantFindErr SLIT("Could not find module")
511 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
512 cannotFindInterface = cantFindErr SLIT("Failed to load interface for")
514 cantFindErr cannot_find dflags mod_name (FoundMultiple pkgs)
515 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
516 sep [ptext SLIT("it was found in multiple packages:"),
517 hsep (map (text.packageIdString) pkgs)]
519 cantFindErr cannot_find dflags mod_name find_result
520 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
524 = case find_result of
526 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
527 <+> ptext SLIT("which is hidden")
530 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
534 -> ptext SLIT("no package matching") <+> ppr pkg <+>
535 ptext SLIT("was found")
537 NotFound files mb_pkg
539 -> ptext SLIT("it is not a module in the current program, or in any known package.")
540 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
542 build = if build_tag == "p" then "profiling"
543 else "\"" ++ build_tag ++ "\""
545 ptext SLIT("Perhaps you haven't installed the ") <> text build <>
546 ptext SLIT(" libraries for package ") <> ppr pkg <> char '?' $$
552 NotFoundInPackage pkg
553 -> ptext SLIT("it is not in package") <+> ppr pkg
555 _ -> panic "cantFindErr"
557 build_tag = buildTag dflags
560 | verbosity dflags < 3
561 = ptext SLIT("Use -v to see a list of the files searched for.")
563 = hang (ptext SLIT("locations searched:")) 2 (vcat (map text files))