2 % (c) The University of Glasgow, 2000-2006
4 \section[Finder]{Module Finder}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
22 addHomeModuleToFinder,
26 findObjectLinkableMaybe,
33 #include "HsVersions.h"
40 import PrelNames ( gHC_PRIM )
41 import DynFlags ( DynFlags(..), isOneShot, GhcMode(..) )
45 import Maybes ( expectJust )
47 import Data.IORef ( IORef, writeIORef, readIORef, modifyIORef )
49 import System.Directory
52 import System.Time ( ClockTime )
55 type FileExt = String -- Filename extension
56 type BaseName = String -- Basename of file
58 -- -----------------------------------------------------------------------------
61 -- The Finder provides a thin filesystem abstraction to the rest of
62 -- the compiler. For a given module, it can tell you where the
63 -- source, interface, and object files for that module live.
65 -- It does *not* know which particular package a module lives in. Use
66 -- Packages.lookupModuleInAllPackages for that.
68 -- -----------------------------------------------------------------------------
71 -- remove all the home modules from the cache; package modules are
72 -- assumed to not move around during a session.
73 flushFinderCaches :: HscEnv -> IO ()
74 flushFinderCaches hsc_env = do
75 writeIORef fc_ref emptyUFM
76 flushModLocationCache this_pkg mlc_ref
78 this_pkg = thisPackage (hsc_dflags hsc_env)
79 fc_ref = hsc_FC hsc_env
80 mlc_ref = hsc_MLC hsc_env
82 flushModLocationCache :: PackageId -> IORef ModLocationCache -> IO ()
83 flushModLocationCache this_pkg ref = do
85 writeIORef ref $! filterFM is_ext fm
87 where is_ext mod _ | modulePackageId mod /= this_pkg = True
90 addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
91 addToFinderCache ref key val = modifyIORef ref $ \c -> addToUFM c key val
93 addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
94 addToModLocationCache ref key val = modifyIORef ref $ \c -> addToFM c key val
96 removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
97 removeFromFinderCache ref key = modifyIORef ref $ \c -> delFromUFM c key
99 removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
100 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
102 lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
103 lookupFinderCache ref key = do
105 return $! lookupUFM c key
107 lookupModLocationCache :: IORef ModLocationCache -> Module
108 -> IO (Maybe ModLocation)
109 lookupModLocationCache ref key = do
111 return $! lookupFM c key
113 -- -----------------------------------------------------------------------------
114 -- The two external entry points
116 -- | Locate a module that was imported by the user. We have the
117 -- module's name, and possibly a package name. Without a package
118 -- name, this function will use the search path and the known exposed
119 -- packages to find the module, if a package is specified then only
120 -- that package is searched for the module.
122 findImportedModule :: HscEnv -> ModuleName -> Maybe PackageId -> IO FindResult
123 findImportedModule hsc_env mod_name mb_pkgid =
125 Nothing -> unqual_import
126 Just pkg | pkg == this_pkg -> home_import
127 | otherwise -> pkg_import pkg
129 dflags = hsc_dflags hsc_env
130 this_pkg = thisPackage dflags
132 home_import = findHomeModule hsc_env mod_name
134 pkg_import pkg = findPackageModule hsc_env (mkModule pkg mod_name)
135 -- ToDo: this isn't quite right, the module we want
136 -- might actually be in another package, but re-exposed
137 -- ToDo: should return NotFoundInPackage if
138 -- the module isn't exposed by the package.
140 unqual_import = home_import
142 findExposedPackageModule hsc_env mod_name
144 -- | Locate a specific 'Module'. The purpose of this function is to
145 -- create a 'ModLocation' for a given 'Module', that is to find out
146 -- where the files associated with this module live. It is used when
147 -- reading the interface for a module mentioned by another interface,
148 -- for example (a "system import").
150 findExactModule :: HscEnv -> Module -> IO FindResult
151 findExactModule hsc_env mod =
152 let dflags = hsc_dflags hsc_env in
153 if modulePackageId mod == thisPackage dflags
154 then findHomeModule hsc_env (moduleName mod)
155 else findPackageModule hsc_env mod
157 -- -----------------------------------------------------------------------------
160 orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
161 this `orIfNotFound` or_this = do
164 NotFound here _ -> do
167 NotFound or_here pkg -> return (NotFound (here ++ or_here) pkg)
168 _other -> return res2
172 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
173 homeSearchCache hsc_env mod_name do_this = do
174 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
176 Just result -> return result
179 addToFinderCache (hsc_FC hsc_env) mod_name result
181 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
185 findExposedPackageModule :: HscEnv -> ModuleName -> IO FindResult
186 findExposedPackageModule hsc_env mod_name
187 -- not found in any package:
188 | null found = return (NotFound [] Nothing)
189 -- found in just one exposed package:
190 | [(pkg_conf, _)] <- found_exposed
191 = let pkgid = mkPackageId (package pkg_conf) in
192 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
193 -- not found in any exposed package, report how it was hidden:
194 | null found_exposed, ((pkg_conf, exposed_mod):_) <- found
195 = let pkgid = mkPackageId (package pkg_conf) in
197 then return (ModuleHidden pkgid)
198 else return (PackageHidden pkgid)
200 = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
202 dflags = hsc_dflags hsc_env
203 found = lookupModuleInAllPackages dflags mod_name
204 found_exposed = filter is_exposed found
205 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
208 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
209 modLocationCache hsc_env mod do_this = do
210 mb_loc <- lookupModLocationCache mlc mod
212 Just loc -> return (Found loc mod)
216 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
220 mlc = hsc_MLC hsc_env
222 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
223 addHomeModuleToFinder hsc_env mod_name loc = do
224 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
225 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
226 addToModLocationCache (hsc_MLC hsc_env) mod loc
229 uncacheModule :: HscEnv -> ModuleName -> IO ()
230 uncacheModule hsc_env mod = do
231 let this_pkg = thisPackage (hsc_dflags hsc_env)
232 removeFromFinderCache (hsc_FC hsc_env) mod
233 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
235 -- -----------------------------------------------------------------------------
236 -- The internal workers
238 -- | Search for a module in the home package only.
239 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
240 findHomeModule hsc_env mod_name =
241 homeSearchCache hsc_env mod_name $
243 dflags = hsc_dflags hsc_env
244 home_path = importPaths dflags
246 mod = mkModule (thisPackage dflags) mod_name
249 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
250 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
253 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
254 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
257 -- In compilation manager modes, we look for source files in the home
258 -- package because we can compile these automatically. In one-shot
259 -- compilation mode we look for .hi and .hi-boot files only.
260 exts | isOneShot (ghcMode dflags) = hi_exts
261 | otherwise = source_exts
264 -- special case for GHC.Prim; we won't find it in the filesystem.
265 -- This is important only when compiling the base package (where GHC.Prim
266 -- is a home module).
268 then return (Found (error "GHC.Prim ModLocation") mod)
271 searchPathExts home_path mod exts
274 -- | Search for a module in external packages only.
275 findPackageModule :: HscEnv -> Module -> IO FindResult
276 findPackageModule hsc_env mod = do
278 dflags = hsc_dflags hsc_env
279 pkg_id = modulePackageId mod
280 pkg_map = pkgIdMap (pkgState dflags)
282 case lookupPackage pkg_map pkg_id of
283 Nothing -> return (NoPackage pkg_id)
284 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
286 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
287 findPackageModule_ hsc_env mod pkg_conf =
288 modLocationCache hsc_env mod $
290 -- special case for GHC.Prim; we won't find it in the filesystem.
292 then return (Found (error "GHC.Prim ModLocation") mod)
296 dflags = hsc_dflags hsc_env
297 tag = buildTag dflags
299 -- hi-suffix for packages depends on the build tag.
300 package_hisuf | null tag = "hi"
301 | otherwise = tag ++ "_hi"
303 [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
306 [ ("hs", mkHiOnlyModLocation dflags package_hisuf)
307 , ("lhs", mkHiOnlyModLocation dflags package_hisuf)
310 -- mkdependHS needs to look for source files in packages too, so
311 -- that we can make dependencies between package before they have
314 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
315 | otherwise = hi_exts
316 -- we never look for a .hi-boot file in an external package;
317 -- .hi-boot files only make sense for the home package.
319 searchPathExts (importDirs pkg_conf) mod exts
321 -- -----------------------------------------------------------------------------
322 -- General path searching
325 :: [FilePath] -- paths to search
326 -> Module -- module name
329 FilePath -> BaseName -> IO ModLocation -- action
334 searchPathExts paths mod exts
335 = do result <- search to_search
337 hPutStrLn stderr (showSDoc $
338 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
339 , nest 2 (vcat (map text paths))
341 Succeeded (loc, p) -> text "Found" <+> ppr loc
342 Failed fs -> text "not found"])
347 basename = dots_to_slashes (moduleNameString (moduleName mod))
349 to_search :: [(FilePath, IO ModLocation)]
350 to_search = [ (file, fn path basename)
353 let base | path == "." = basename
354 | otherwise = path `joinFileName` basename
355 file = base `joinFileExt` ext
358 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
359 search ((file, mk_result) : rest) = do
360 b <- doesFileExist file
362 then do { loc <- mk_result; return (Found loc mod) }
365 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
366 -> FilePath -> BaseName -> IO ModLocation
367 mkHomeModLocationSearched dflags mod suff path basename = do
368 mkHomeModLocation2 dflags mod (path `joinFileName` basename) suff
370 -- -----------------------------------------------------------------------------
371 -- Constructing a home module location
373 -- This is where we construct the ModLocation for a module in the home
374 -- package, for which we have a source file. It is called from three
377 -- (a) Here in the finder, when we are searching for a module to import,
378 -- using the search path (-i option).
380 -- (b) The compilation manager, when constructing the ModLocation for
381 -- a "root" module (a source file named explicitly on the command line
382 -- or in a :load command in GHCi).
384 -- (c) The driver in one-shot mode, when we need to construct a
385 -- ModLocation for a source file named on the command-line.
390 -- The name of the module
393 -- (a): The search path component where the source file was found.
397 -- (a): dots_to_slashes (moduleNameUserString mod)
398 -- (b) and (c): The filename of the source file, minus its extension
401 -- The filename extension of the source file (usually "hs" or "lhs").
403 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
404 mkHomeModLocation dflags mod src_filename = do
405 let (basename,extension) = splitFilename src_filename
406 mkHomeModLocation2 dflags mod basename extension
408 mkHomeModLocation2 :: DynFlags
410 -> FilePath -- Of source module, without suffix
413 mkHomeModLocation2 dflags mod src_basename ext = do
414 let mod_basename = dots_to_slashes (moduleNameString mod)
416 obj_fn <- mkObjPath dflags src_basename mod_basename
417 hi_fn <- mkHiPath dflags src_basename mod_basename
419 return (ModLocation{ ml_hs_file = Just (src_basename `joinFileExt` ext),
421 ml_obj_file = obj_fn })
423 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
425 mkHiOnlyModLocation dflags hisuf path basename
426 = do let full_basename = path `joinFileName` basename
427 obj_fn <- mkObjPath dflags full_basename basename
428 return ModLocation{ ml_hs_file = Nothing,
429 ml_hi_file = full_basename `joinFileExt` hisuf,
430 -- Remove the .hi-boot suffix from
431 -- hi_file, if it had one. We always
432 -- want the name of the real .hi file
433 -- in the ml_hi_file field.
437 -- | Constructs the filename of a .o file for a given source file.
438 -- Does /not/ check whether the .o file exists
441 -> FilePath -- the filename of the source file, minus the extension
442 -> String -- the module name with dots replaced by slashes
444 mkObjPath dflags basename mod_basename
446 odir = objectDir dflags
447 osuf = objectSuf dflags
449 obj_basename | Just dir <- odir = dir `joinFileName` mod_basename
450 | otherwise = basename
452 return (obj_basename `joinFileExt` osuf)
454 -- | Constructs the filename of a .hi file for a given source file.
455 -- Does /not/ check whether the .hi file exists
458 -> FilePath -- the filename of the source file, minus the extension
459 -> String -- the module name with dots replaced by slashes
461 mkHiPath dflags basename mod_basename
466 hi_basename | Just dir <- hidir = dir `joinFileName` mod_basename
467 | otherwise = basename
469 return (hi_basename `joinFileExt` hisuf)
472 -- -----------------------------------------------------------------------------
473 -- Filenames of the stub files
475 -- We don't have to store these in ModLocations, because they can be derived
476 -- from other available information, and they're only rarely needed.
482 -> (FilePath,FilePath,FilePath)
484 mkStubPaths dflags mod location
486 stubdir = stubDir dflags
488 mod_basename = dots_to_slashes (moduleNameString mod)
489 src_basename = basenameOf (expectJust "mkStubPaths"
490 (ml_hs_file location))
493 | Just dir <- stubdir = dir `joinFileName` mod_basename
494 | otherwise = src_basename
496 stub_basename = stub_basename0 ++ "_stub"
498 -- this is the filename we're going to use when
499 -- #including the stub_h file from the .hc file.
500 -- Without -stubdir, we just #include the basename
501 -- (eg. for a module A.B, we #include "B_stub.h"),
502 -- relying on the fact that we add an implicit -I flag
503 -- for the directory in which the source file resides
504 -- (see DriverPipeline.hs). With -stubdir, we
505 -- #include "A/B.h", assuming that the user has added
506 -- -I<dir> along with -stubdir <dir>.
508 | Just _ <- stubdir = mod_basename
509 | otherwise = filenameOf src_basename
511 (stub_basename `joinFileExt` "c",
512 stub_basename `joinFileExt` "h",
513 (include_basename ++ "_stub") `joinFileExt` "h")
514 -- the _stub.o filename is derived from the ml_obj_file.
516 -- -----------------------------------------------------------------------------
517 -- findLinkable isn't related to the other stuff in here,
518 -- but there's no other obvious place for it
520 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
521 findObjectLinkableMaybe mod locn
522 = do let obj_fn = ml_obj_file locn
523 maybe_obj_time <- modificationTimeIfExists obj_fn
524 case maybe_obj_time of
525 Nothing -> return Nothing
526 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
528 -- Make an object linkable when we know the object file exists, and we know
529 -- its modification time.
530 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
531 findObjectLinkable mod obj_fn obj_time = do
532 let stub_fn = case splitFilename3 obj_fn of
533 (dir, base, ext) -> dir ++ "/" ++ base ++ "_stub.o"
534 stub_exist <- doesFileExist stub_fn
536 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
537 else return (LM obj_time mod [DotO obj_fn])
539 -- -----------------------------------------------------------------------------
542 dots_to_slashes :: String -> String
543 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
545 -- -----------------------------------------------------------------------------
548 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
549 cannotFindModule = cantFindErr SLIT("Could not find module")
551 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
552 cannotFindInterface = cantFindErr SLIT("Failed to load interface for")
554 cantFindErr :: LitString -> DynFlags -> ModuleName -> FindResult -> SDoc
555 cantFindErr cannot_find _dflags mod_name (FoundMultiple pkgs)
556 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
557 sep [ptext SLIT("it was found in multiple packages:"),
558 hsep (map (text.packageIdString) pkgs)]
560 cantFindErr cannot_find dflags mod_name find_result
561 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
565 = case find_result of
567 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
568 <+> ptext SLIT("which is hidden")
571 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
575 -> ptext SLIT("no package matching") <+> ppr pkg <+>
576 ptext SLIT("was found")
578 NotFound files mb_pkg
580 -> ptext SLIT("it is not a module in the current program, or in any known package.")
581 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
583 build = if build_tag == "p" then "profiling"
584 else "\"" ++ build_tag ++ "\""
586 ptext SLIT("Perhaps you haven't installed the ") <> text build <>
587 ptext SLIT(" libraries for package ") <> ppr pkg <> char '?' $$
593 NotFoundInPackage pkg
594 -> ptext SLIT("it is not in package") <+> ppr pkg
596 _ -> panic "cantFindErr"
598 build_tag = buildTag dflags
601 | verbosity dflags < 3
602 = ptext SLIT("Use -v to see a list of the files searched for.")
604 = hang (ptext SLIT("locations searched:")) 2 (vcat (map text files))