2 % (c) The University of Glasgow, 2000-2006
4 \section[Finder]{Module Finder}
16 addHomeModuleToFinder,
20 findObjectLinkableMaybe,
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
43 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 PackageId -> IO FindResult
117 findImportedModule hsc_env mod_name mb_pkgid =
119 Nothing -> unqual_import
120 Just pkg | pkg == this_pkg -> home_import
121 | otherwise -> pkg_import pkg
123 dflags = hsc_dflags hsc_env
124 this_pkg = thisPackage dflags
126 home_import = findHomeModule hsc_env mod_name
128 pkg_import pkg = findPackageModule hsc_env (mkModule pkg mod_name)
129 -- ToDo: this isn't quite right, the module we want
130 -- might actually be in another package, but re-exposed
131 -- ToDo: should return NotFoundInPackage if
132 -- the module isn't exposed by the package.
134 unqual_import = home_import
136 findExposedPackageModule hsc_env mod_name
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 here _ -> do
161 NotFound or_here pkg -> return (NotFound (here ++ or_here) pkg)
162 _other -> return res2
166 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
167 homeSearchCache hsc_env mod_name do_this = do
168 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
170 Just result -> return result
173 addToFinderCache (hsc_FC hsc_env) mod_name result
175 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
179 findExposedPackageModule :: HscEnv -> ModuleName -> IO FindResult
180 findExposedPackageModule hsc_env mod_name
181 -- not found in any package:
182 | null found = return (NotFound [] Nothing)
183 -- found in just one exposed package:
184 | [(pkg_conf, _)] <- found_exposed
185 = let pkgid = mkPackageId (package pkg_conf) in
186 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
187 -- not found in any exposed package, report how it was hidden:
188 | null found_exposed, ((pkg_conf, exposed_mod):_) <- found
189 = let pkgid = mkPackageId (package pkg_conf) in
191 then return (ModuleHidden pkgid)
192 else return (PackageHidden pkgid)
194 = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
196 dflags = hsc_dflags hsc_env
197 found = lookupModuleInAllPackages dflags mod_name
198 found_exposed = filter is_exposed found
199 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
202 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
203 modLocationCache hsc_env mod do_this = do
204 mb_loc <- lookupModLocationCache mlc mod
206 Just loc -> return (Found loc mod)
210 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
214 mlc = hsc_MLC hsc_env
216 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
217 addHomeModuleToFinder hsc_env mod_name loc = do
218 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
219 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
220 addToModLocationCache (hsc_MLC hsc_env) mod loc
223 uncacheModule :: HscEnv -> ModuleName -> IO ()
224 uncacheModule hsc_env mod = do
225 let this_pkg = thisPackage (hsc_dflags hsc_env)
226 removeFromFinderCache (hsc_FC hsc_env) mod
227 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
229 -- -----------------------------------------------------------------------------
230 -- The internal workers
232 -- | Search for a module in the home package only.
233 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
234 findHomeModule hsc_env mod_name =
235 homeSearchCache hsc_env mod_name $
237 dflags = hsc_dflags hsc_env
238 home_path = importPaths dflags
240 mod = mkModule (thisPackage dflags) mod_name
243 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
244 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
247 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
248 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
251 -- In compilation manager modes, we look for source files in the home
252 -- package because we can compile these automatically. In one-shot
253 -- compilation mode we look for .hi and .hi-boot files only.
254 exts | isOneShot (ghcMode dflags) = hi_exts
255 | otherwise = source_exts
258 -- special case for GHC.Prim; we won't find it in the filesystem.
259 -- This is important only when compiling the base package (where GHC.Prim
260 -- is a home module).
262 then return (Found (error "GHC.Prim ModLocation") mod)
265 searchPathExts home_path mod exts
268 -- | Search for a module in external packages only.
269 findPackageModule :: HscEnv -> Module -> IO FindResult
270 findPackageModule hsc_env mod = do
272 dflags = hsc_dflags hsc_env
273 pkg_id = modulePackageId mod
274 pkg_map = pkgIdMap (pkgState dflags)
276 case lookupPackage pkg_map pkg_id of
277 Nothing -> return (NoPackage pkg_id)
278 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
280 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
281 findPackageModule_ hsc_env mod pkg_conf =
282 modLocationCache hsc_env mod $
284 -- special case for GHC.Prim; we won't find it in the filesystem.
286 then return (Found (error "GHC.Prim ModLocation") mod)
290 dflags = hsc_dflags hsc_env
291 tag = buildTag dflags
293 -- hi-suffix for packages depends on the build tag.
294 package_hisuf | null tag = "hi"
295 | otherwise = tag ++ "_hi"
297 [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
300 [ ("hs", mkHiOnlyModLocation dflags package_hisuf)
301 , ("lhs", mkHiOnlyModLocation dflags package_hisuf)
304 -- mkdependHS needs to look for source files in packages too, so
305 -- that we can make dependencies between package before they have
308 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
309 | otherwise = hi_exts
310 -- we never look for a .hi-boot file in an external package;
311 -- .hi-boot files only make sense for the home package.
313 searchPathExts (importDirs pkg_conf) mod exts
315 -- -----------------------------------------------------------------------------
316 -- General path searching
319 :: [FilePath] -- paths to search
320 -> Module -- module name
323 FilePath -> BaseName -> IO ModLocation -- action
328 searchPathExts paths mod exts
329 = do result <- search to_search
331 hPutStrLn stderr (showSDoc $
332 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
333 , nest 2 (vcat (map text paths))
335 Succeeded (loc, p) -> text "Found" <+> ppr loc
336 Failed fs -> text "not found"])
341 basename = moduleNameSlashes (moduleName mod)
343 to_search :: [(FilePath, IO ModLocation)]
344 to_search = [ (file, fn path basename)
347 let base | path == "." = basename
348 | otherwise = path </> basename
352 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
353 search ((file, mk_result) : rest) = do
354 b <- doesFileExist file
356 then do { loc <- mk_result; return (Found loc mod) }
359 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
360 -> FilePath -> BaseName -> IO ModLocation
361 mkHomeModLocationSearched dflags mod suff path basename = do
362 mkHomeModLocation2 dflags mod (path </> basename) suff
364 -- -----------------------------------------------------------------------------
365 -- Constructing a home module location
367 -- This is where we construct the ModLocation for a module in the home
368 -- package, for which we have a source file. It is called from three
371 -- (a) Here in the finder, when we are searching for a module to import,
372 -- using the search path (-i option).
374 -- (b) The compilation manager, when constructing the ModLocation for
375 -- a "root" module (a source file named explicitly on the command line
376 -- or in a :load command in GHCi).
378 -- (c) The driver in one-shot mode, when we need to construct a
379 -- ModLocation for a source file named on the command-line.
384 -- The name of the module
387 -- (a): The search path component where the source file was found.
391 -- (a): (moduleNameSlashes mod)
392 -- (b) and (c): The filename of the source file, minus its extension
395 -- The filename extension of the source file (usually "hs" or "lhs").
397 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
398 mkHomeModLocation dflags mod src_filename = do
399 let (basename,extension) = splitExtension src_filename
400 mkHomeModLocation2 dflags mod basename extension
402 mkHomeModLocation2 :: DynFlags
404 -> FilePath -- Of source module, without suffix
407 mkHomeModLocation2 dflags mod src_basename ext = do
408 let mod_basename = moduleNameSlashes mod
410 obj_fn <- mkObjPath dflags src_basename mod_basename
411 hi_fn <- mkHiPath dflags src_basename mod_basename
413 return (ModLocation{ ml_hs_file = Just (src_basename <.> ext),
415 ml_obj_file = obj_fn })
417 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
419 mkHiOnlyModLocation dflags hisuf path basename
420 = do let full_basename = path </> basename
421 obj_fn <- mkObjPath dflags full_basename basename
422 return ModLocation{ ml_hs_file = Nothing,
423 ml_hi_file = full_basename <.> hisuf,
424 -- Remove the .hi-boot suffix from
425 -- hi_file, if it had one. We always
426 -- want the name of the real .hi file
427 -- in the ml_hi_file field.
431 -- | Constructs the filename of a .o file for a given source file.
432 -- Does /not/ check whether the .o file exists
435 -> FilePath -- the filename of the source file, minus the extension
436 -> String -- the module name with dots replaced by slashes
438 mkObjPath dflags basename mod_basename
440 odir = objectDir dflags
441 osuf = objectSuf dflags
443 obj_basename | Just dir <- odir = dir </> mod_basename
444 | otherwise = basename
446 return (obj_basename <.> osuf)
448 -- | Constructs the filename of a .hi file for a given source file.
449 -- Does /not/ check whether the .hi file exists
452 -> FilePath -- the filename of the source file, minus the extension
453 -> String -- the module name with dots replaced by slashes
455 mkHiPath dflags basename mod_basename
460 hi_basename | Just dir <- hidir = dir </> mod_basename
461 | otherwise = basename
463 return (hi_basename <.> hisuf)
466 -- -----------------------------------------------------------------------------
467 -- Filenames of the stub files
469 -- We don't have to store these in ModLocations, because they can be derived
470 -- from other available information, and they're only rarely needed.
476 -> (FilePath,FilePath,FilePath)
478 mkStubPaths dflags mod location
480 stubdir = stubDir dflags
482 mod_basename = moduleNameSlashes mod
483 src_basename = dropExtension $ expectJust "mkStubPaths"
484 (ml_hs_file location)
487 | Just dir <- stubdir = dir </> mod_basename
488 | otherwise = src_basename
490 stub_basename = stub_basename0 ++ "_stub"
492 -- this is the filename we're going to use when
493 -- #including the stub_h file from the .hc file.
494 -- Without -stubdir, we just #include the basename
495 -- (eg. for a module A.B, we #include "B_stub.h"),
496 -- relying on the fact that we add an implicit -I flag
497 -- for the directory in which the source file resides
498 -- (see DriverPipeline.hs). With -stubdir, we
499 -- #include "A/B.h", assuming that the user has added
500 -- -I<dir> along with -stubdir <dir>.
502 | Just _ <- stubdir = mod_basename
503 | otherwise = takeFileName src_basename
505 (stub_basename <.> "c",
506 stub_basename <.> "h",
507 (include_basename ++ "_stub") <.> "h")
508 -- the _stub.o filename is derived from the ml_obj_file.
510 -- -----------------------------------------------------------------------------
511 -- findLinkable isn't related to the other stuff in here,
512 -- but there's no other obvious place for it
514 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
515 findObjectLinkableMaybe mod locn
516 = do let obj_fn = ml_obj_file locn
517 maybe_obj_time <- modificationTimeIfExists obj_fn
518 case maybe_obj_time of
519 Nothing -> return Nothing
520 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
522 -- Make an object linkable when we know the object file exists, and we know
523 -- its modification time.
524 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
525 findObjectLinkable mod obj_fn obj_time = do
526 let stub_fn = (dropExtension obj_fn ++ "_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 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
536 cannotFindModule = cantFindErr (sLit "Could not find module")
538 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
539 cannotFindInterface = cantFindErr (sLit "Failed to load interface for")
541 cantFindErr :: LitString -> DynFlags -> ModuleName -> FindResult -> SDoc
542 cantFindErr cannot_find _dflags mod_name (FoundMultiple pkgs)
543 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
544 sep [ptext (sLit "it was found in multiple packages:"),
545 hsep (map (text.packageIdString) pkgs)]
547 cantFindErr cannot_find dflags mod_name find_result
548 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
552 = case find_result of
554 -> ptext (sLit "it is a member of package") <+> ppr pkg <> comma
555 <+> ptext (sLit "which is hidden")
558 -> ptext (sLit "it is hidden") <+> parens (ptext (sLit "in package")
562 -> ptext (sLit "no package matching") <+> ppr pkg <+>
563 ptext (sLit "was found")
565 NotFound files mb_pkg
567 -> ptext (sLit "it is not a module in the current program, or in any known package.")
568 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
570 build = if build_tag == "p" then "profiling"
571 else "\"" ++ build_tag ++ "\""
573 ptext (sLit "Perhaps you haven't installed the ") <> text build <>
574 ptext (sLit " libraries for package ") <> ppr pkg <> char '?' $$
580 NotFoundInPackage pkg
581 -> ptext (sLit "it is not in package") <+> ppr pkg
583 _ -> panic "cantFindErr"
585 build_tag = buildTag dflags
588 | verbosity dflags < 3
589 = ptext (sLit "Use -v to see a list of the files searched for.")
591 = hang (ptext (sLit "locations searched:")) 2 (vcat (map text files))