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 ref key val = modifyIORef ref $ \c -> addToUFM c key val
91 addToModLocationCache ref key val = modifyIORef ref $ \c -> addToFM c key val
93 removeFromFinderCache ref key = modifyIORef ref $ \c -> delFromUFM c key
94 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
96 lookupFinderCache ref key = do
98 return $! lookupUFM c key
100 lookupModLocationCache ref key = do
102 return $! lookupFM c key
104 -- -----------------------------------------------------------------------------
105 -- The two external entry points
107 -- | Locate a module that was imported by the user. We have the
108 -- module's name, and possibly a package name. Without a package
109 -- name, this function will use the search path and the known exposed
110 -- packages to find the module, if a package is specified then only
111 -- that package is searched for the module.
113 findImportedModule :: HscEnv -> ModuleName -> Maybe PackageId -> IO FindResult
114 findImportedModule hsc_env mod_name mb_pkgid =
116 Nothing -> unqual_import
117 Just pkg | pkg == this_pkg -> home_import
118 | otherwise -> pkg_import pkg
120 dflags = hsc_dflags hsc_env
121 this_pkg = thisPackage dflags
123 home_import = findHomeModule hsc_env mod_name
125 pkg_import pkg = findPackageModule hsc_env (mkModule pkg mod_name)
126 -- ToDo: this isn't quite right, the module we want
127 -- might actually be in another package, but re-exposed
128 -- ToDo: should return NotFoundInPackage if
129 -- the module isn't exposed by the package.
131 unqual_import = home_import
133 findExposedPackageModule hsc_env mod_name
135 -- | Locate a specific 'Module'. The purpose of this function is to
136 -- create a 'ModLocation' for a given 'Module', that is to find out
137 -- where the files associated with this module live. It is used when
138 -- reading the interface for a module mentioned by another interface,
139 -- for example (a "system import").
141 findExactModule :: HscEnv -> Module -> IO FindResult
142 findExactModule hsc_env mod =
143 let dflags = hsc_dflags hsc_env in
144 if modulePackageId mod == thisPackage dflags
145 then findHomeModule hsc_env (moduleName mod)
146 else findPackageModule hsc_env mod
148 -- -----------------------------------------------------------------------------
151 this `orIfNotFound` or_this = do
154 NotFound here _ -> do
157 NotFound or_here pkg -> return (NotFound (here ++ or_here) pkg)
158 _other -> return res2
162 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
163 homeSearchCache hsc_env mod_name do_this = do
164 m <- lookupFinderCache (hsc_FC hsc_env) mod_name
166 Just result -> return result
169 addToFinderCache (hsc_FC hsc_env) mod_name result
171 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
175 findExposedPackageModule :: HscEnv -> ModuleName -> IO FindResult
176 findExposedPackageModule hsc_env mod_name
177 -- not found in any package:
178 | null found = return (NotFound [] Nothing)
179 -- found in just one exposed package:
180 | [(pkg_conf, _)] <- found_exposed
181 = let pkgid = mkPackageId (package pkg_conf) in
182 findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
183 -- not found in any exposed package, report how it was hidden:
184 | null found_exposed, ((pkg_conf, exposed_mod):_) <- found
185 = let pkgid = mkPackageId (package pkg_conf) in
187 then return (ModuleHidden pkgid)
188 else return (PackageHidden pkgid)
190 = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
192 dflags = hsc_dflags hsc_env
193 found = lookupModuleInAllPackages dflags mod_name
194 found_exposed = filter is_exposed found
195 is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
198 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
199 modLocationCache hsc_env mod do_this = do
200 mb_loc <- lookupModLocationCache mlc mod
202 Just loc -> return (Found loc mod)
206 Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
210 mlc = hsc_MLC hsc_env
212 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
213 addHomeModuleToFinder hsc_env mod_name loc = do
214 let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
215 addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
216 addToModLocationCache (hsc_MLC hsc_env) mod loc
219 uncacheModule :: HscEnv -> ModuleName -> IO ()
220 uncacheModule hsc_env mod = do
221 let this_pkg = thisPackage (hsc_dflags hsc_env)
222 removeFromFinderCache (hsc_FC hsc_env) mod
223 removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
225 -- -----------------------------------------------------------------------------
226 -- The internal workers
228 -- | Search for a module in the home package only.
229 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
230 findHomeModule hsc_env mod_name =
231 homeSearchCache hsc_env mod_name $
233 dflags = hsc_dflags hsc_env
234 home_path = importPaths dflags
236 mod = mkModule (thisPackage dflags) mod_name
239 [ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
240 , ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
243 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
244 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
247 -- In compilation manager modes, we look for source files in the home
248 -- package because we can compile these automatically. In one-shot
249 -- compilation mode we look for .hi and .hi-boot files only.
250 exts | isOneShot (ghcMode dflags) = hi_exts
251 | otherwise = source_exts
254 -- special case for GHC.Prim; we won't find it in the filesystem.
255 -- This is important only when compiling the base package (where GHC.Prim
256 -- is a home module).
258 then return (Found (error "GHC.Prim ModLocation") mod)
261 searchPathExts home_path mod exts
264 -- | Search for a module in external packages only.
265 findPackageModule :: HscEnv -> Module -> IO FindResult
266 findPackageModule hsc_env mod = do
268 dflags = hsc_dflags hsc_env
269 pkg_id = modulePackageId mod
270 pkg_map = pkgIdMap (pkgState dflags)
272 case lookupPackage pkg_map pkg_id of
273 Nothing -> return (NoPackage pkg_id)
274 Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
276 findPackageModule_ hsc_env mod pkg_conf =
277 modLocationCache hsc_env mod $
279 -- special case for GHC.Prim; we won't find it in the filesystem.
281 then return (Found (error "GHC.Prim ModLocation") mod)
285 dflags = hsc_dflags hsc_env
286 tag = buildTag dflags
288 -- hi-suffix for packages depends on the build tag.
289 package_hisuf | null tag = "hi"
290 | otherwise = tag ++ "_hi"
292 [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
295 [ ("hs", mkHiOnlyModLocation dflags package_hisuf)
296 , ("lhs", mkHiOnlyModLocation dflags package_hisuf)
299 -- mkdependHS needs to look for source files in packages too, so
300 -- that we can make dependencies between package before they have
303 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
304 | otherwise = hi_exts
305 -- we never look for a .hi-boot file in an external package;
306 -- .hi-boot files only make sense for the home package.
308 searchPathExts (importDirs pkg_conf) mod exts
310 -- -----------------------------------------------------------------------------
311 -- General path searching
314 :: [FilePath] -- paths to search
315 -> Module -- module name
318 FilePath -> BaseName -> IO ModLocation -- action
323 searchPathExts paths mod exts
324 = do result <- search to_search
326 hPutStrLn stderr (showSDoc $
327 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
328 , nest 2 (vcat (map text paths))
330 Succeeded (loc, p) -> text "Found" <+> ppr loc
331 Failed fs -> text "not found"])
336 basename = dots_to_slashes (moduleNameString (moduleName mod))
338 to_search :: [(FilePath, IO ModLocation)]
339 to_search = [ (file, fn path basename)
342 let base | path == "." = basename
343 | otherwise = path `joinFileName` basename
344 file = base `joinFileExt` ext
347 search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
348 search ((file, mk_result) : rest) = do
349 b <- doesFileExist file
351 then do { loc <- mk_result; return (Found loc mod) }
354 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
355 -> FilePath -> BaseName -> IO ModLocation
356 mkHomeModLocationSearched dflags mod suff path basename = do
357 mkHomeModLocation2 dflags mod (path `joinFileName` basename) suff
359 -- -----------------------------------------------------------------------------
360 -- Constructing a home module location
362 -- This is where we construct the ModLocation for a module in the home
363 -- package, for which we have a source file. It is called from three
366 -- (a) Here in the finder, when we are searching for a module to import,
367 -- using the search path (-i option).
369 -- (b) The compilation manager, when constructing the ModLocation for
370 -- a "root" module (a source file named explicitly on the command line
371 -- or in a :load command in GHCi).
373 -- (c) The driver in one-shot mode, when we need to construct a
374 -- ModLocation for a source file named on the command-line.
379 -- The name of the module
382 -- (a): The search path component where the source file was found.
386 -- (a): dots_to_slashes (moduleNameUserString mod)
387 -- (b) and (c): The filename of the source file, minus its extension
390 -- The filename extension of the source file (usually "hs" or "lhs").
392 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
393 mkHomeModLocation dflags mod src_filename = do
394 let (basename,extension) = splitFilename src_filename
395 mkHomeModLocation2 dflags mod basename extension
397 mkHomeModLocation2 :: DynFlags
399 -> FilePath -- Of source module, without suffix
402 mkHomeModLocation2 dflags mod src_basename ext = do
403 let mod_basename = dots_to_slashes (moduleNameString mod)
405 obj_fn <- mkObjPath dflags src_basename mod_basename
406 hi_fn <- mkHiPath dflags src_basename mod_basename
408 return (ModLocation{ ml_hs_file = Just (src_basename `joinFileExt` ext),
410 ml_obj_file = obj_fn })
412 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
414 mkHiOnlyModLocation dflags hisuf path basename
415 = do let full_basename = path `joinFileName` basename
416 obj_fn <- mkObjPath dflags full_basename basename
417 return ModLocation{ ml_hs_file = Nothing,
418 ml_hi_file = full_basename `joinFileExt` hisuf,
419 -- Remove the .hi-boot suffix from
420 -- hi_file, if it had one. We always
421 -- want the name of the real .hi file
422 -- in the ml_hi_file field.
426 -- | Constructs the filename of a .o file for a given source file.
427 -- Does /not/ check whether the .o file exists
430 -> FilePath -- the filename of the source file, minus the extension
431 -> String -- the module name with dots replaced by slashes
433 mkObjPath dflags basename mod_basename
435 odir = objectDir dflags
436 osuf = objectSuf dflags
438 obj_basename | Just dir <- odir = dir `joinFileName` mod_basename
439 | otherwise = basename
441 return (obj_basename `joinFileExt` osuf)
443 -- | Constructs the filename of a .hi file for a given source file.
444 -- Does /not/ check whether the .hi file exists
447 -> FilePath -- the filename of the source file, minus the extension
448 -> String -- the module name with dots replaced by slashes
450 mkHiPath dflags basename mod_basename
455 hi_basename | Just dir <- hidir = dir `joinFileName` mod_basename
456 | otherwise = basename
458 return (hi_basename `joinFileExt` hisuf)
461 -- -----------------------------------------------------------------------------
462 -- Filenames of the stub files
464 -- We don't have to store these in ModLocations, because they can be derived
465 -- from other available information, and they're only rarely needed.
471 -> (FilePath,FilePath)
473 mkStubPaths dflags mod location
475 stubdir = stubDir dflags
477 mod_basename = dots_to_slashes (moduleNameString mod)
478 src_basename = basenameOf (expectJust "mkStubPaths"
479 (ml_hs_file location))
482 | Just dir <- stubdir = dir `joinFileName` mod_basename
483 | otherwise = src_basename
485 stub_basename = stub_basename0 ++ "_stub"
487 (stub_basename `joinFileExt` "c",
488 stub_basename `joinFileExt` "h")
489 -- the _stub.o filename is derived from the ml_obj_file.
491 -- -----------------------------------------------------------------------------
492 -- findLinkable isn't related to the other stuff in here,
493 -- but there's no other obvious place for it
495 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
496 findObjectLinkableMaybe mod locn
497 = do let obj_fn = ml_obj_file locn
498 maybe_obj_time <- modificationTimeIfExists obj_fn
499 case maybe_obj_time of
500 Nothing -> return Nothing
501 Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
503 -- Make an object linkable when we know the object file exists, and we know
504 -- its modification time.
505 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
506 findObjectLinkable mod obj_fn obj_time = do
507 let stub_fn = case splitFilename3 obj_fn of
508 (dir, base, ext) -> dir ++ "/" ++ base ++ "_stub.o"
509 stub_exist <- doesFileExist stub_fn
511 then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
512 else return (LM obj_time mod [DotO obj_fn])
514 -- -----------------------------------------------------------------------------
517 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
520 -- -----------------------------------------------------------------------------
523 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
524 cannotFindModule = cantFindErr SLIT("Could not find module")
526 cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
527 cannotFindInterface = cantFindErr SLIT("Failed to load interface for")
529 cantFindErr cannot_find dflags mod_name (FoundMultiple pkgs)
530 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
531 sep [ptext SLIT("it was found in multiple packages:"),
532 hsep (map (text.packageIdString) pkgs)]
534 cantFindErr cannot_find dflags mod_name find_result
535 = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
539 = case find_result of
541 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
542 <+> ptext SLIT("which is hidden")
545 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
549 -> ptext SLIT("no package matching") <+> ppr pkg <+>
550 ptext SLIT("was found")
552 NotFound files mb_pkg
554 -> ptext SLIT("it is not a module in the current program, or in any known package.")
555 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
557 build = if build_tag == "p" then "profiling"
558 else "\"" ++ build_tag ++ "\""
560 ptext SLIT("Perhaps you haven't installed the ") <> text build <>
561 ptext SLIT(" libraries for package ") <> ppr pkg <> char '?' $$
567 NotFoundInPackage pkg
568 -> ptext SLIT("it is not in package") <+> ppr pkg
570 _ -> panic "cantFindErr"
572 build_tag = buildTag dflags
575 | verbosity dflags < 3
576 = ptext SLIT("Use -v to see a list of the files searched for.")
578 = hang (ptext SLIT("locations searched:")) 2 (vcat (map text files))