2 % (c) The University of Glasgow, 2000
4 \section[Finder]{Module Finder}
8 flushFinderCache, -- :: IO ()
10 findModule, -- :: ModuleName -> Bool -> IO FindResult
11 findPackageModule, -- :: ModuleName -> Bool -> IO FindResult
12 mkHomeModLocation, -- :: ModuleName -> FilePath -> IO ModLocation
13 mkHomeModLocation2, -- :: ModuleName -> FilePath -> String -> IO ModLocation
14 addHomeModuleToFinder, -- :: Module -> ModLocation -> IO ()
16 findLinkable, -- :: ModuleName -> ModLocation -> IO (Maybe Linkable)
18 cantFindError, -- :: DynFlags -> Module -> FindResult -> SDoc
21 #include "HsVersions.h"
24 import UniqFM ( filterUFM )
25 import HscTypes ( Linkable(..), Unlinked(..) )
29 import DynFlags ( DynFlags(..), isOneShot, GhcMode(..) )
32 import DATA_IOREF ( IORef, writeIORef, readIORef )
35 import System.Directory
38 import Maybes ( MaybeErr(..) )
39 import Data.Maybe ( isNothing )
42 type FileExt = String -- Filename extension
43 type BaseName = String -- Basename of file
45 -- -----------------------------------------------------------------------------
48 -- The Finder provides a thin filesystem abstraction to the rest of
49 -- the compiler. For a given module, it can tell you where the
50 -- source, interface, and object files for that module live.
52 -- It does *not* know which particular package a module lives in. Use
53 -- Packages.moduleToPackageConfig for that.
55 -- -----------------------------------------------------------------------------
58 GLOBAL_VAR(finder_cache, emptyModuleEnv, ModuleEnv FinderCacheEntry)
60 type FinderCacheEntry = (ModLocation, Maybe (PackageConfig,Bool))
62 -- remove all the home modules from the cache; package modules are
63 -- assumed to not move around during a session.
64 flushFinderCache :: IO ()
66 fm <- readIORef finder_cache
67 writeIORef finder_cache (filterUFM (\(loc,m) -> isNothing m) fm)
69 addToFinderCache :: Module -> FinderCacheEntry -> IO ()
70 addToFinderCache mod_name entry = do
71 fm <- readIORef finder_cache
72 writeIORef finder_cache (extendModuleEnv fm mod_name entry)
74 lookupFinderCache :: Module -> IO (Maybe FinderCacheEntry)
75 lookupFinderCache mod_name = do
76 fm <- readIORef finder_cache
77 return $! lookupModuleEnv fm mod_name
79 -- -----------------------------------------------------------------------------
82 -- This is the main interface to the finder, which maps ModuleNames to
83 -- Modules and ModLocations.
85 -- The Module contains one crucial bit of information about a module:
86 -- whether it lives in the current ("home") package or not (see Module
89 -- The ModLocation contains the names of all the files associated with
90 -- that module: its source file, .hi file, object file, etc.
93 = Found ModLocation PackageIdH
94 -- the module was found
95 | PackageHidden PackageId
96 -- for an explicit source import: the package containing the module is
98 | ModuleHidden PackageId
99 -- for an explicit source import: the package containing the module is
100 -- exposed, but the module itself is hidden.
101 | NotFound [FilePath]
102 -- the module was not found, the specified places were searched.
104 type LocalFindResult = MaybeErr [FilePath] FinderCacheEntry
105 -- LocalFindResult is used for internal functions which
106 -- return a more informative type; it's munged into
107 -- the external FindResult by 'cached'
110 -> (DynFlags -> Module -> IO LocalFindResult)
111 -> DynFlags -> Module -> Bool -> IO FindResult
112 cached home_allowed wrapped_fn dflags name explicit
113 = do { -- First try the cache
114 mb_entry <- lookupFinderCache name
116 Just old_entry -> return (found old_entry) ;
119 { -- Now try the wrapped function
120 mb_entry <- wrapped_fn dflags name
122 Failed paths -> return (NotFound paths)
123 Succeeded new_entry -> do { addToFinderCache name new_entry
124 ; return (found new_entry) }
127 -- We've found the module, so the remaining question is
128 -- whether it's visible or not
129 found :: FinderCacheEntry -> FindResult
131 | home_allowed = Found loc HomePackage
132 | otherwise = NotFound []
133 found (loc, Just (pkg, exposed_mod))
134 | explicit && not exposed_mod = ModuleHidden pkg_name
135 | explicit && not (exposed pkg) = PackageHidden pkg_name
136 | otherwise = Found loc (ExtPackage (mkPackageId (package pkg)))
138 pkg_name = packageConfigId pkg
140 addHomeModuleToFinder :: Module -> ModLocation -> IO ()
141 addHomeModuleToFinder mod loc = addToFinderCache mod (loc, Nothing)
144 -- -----------------------------------------------------------------------------
145 -- The two external entry points
148 findModule :: DynFlags -> Module -> Bool -> IO FindResult
149 findModule = cached True findModule'
151 findPackageModule :: DynFlags -> Module -> Bool -> IO FindResult
152 findPackageModule = cached False findPackageModule'
154 -- -----------------------------------------------------------------------------
155 -- The internal workers
157 findModule' :: DynFlags -> Module -> IO LocalFindResult
158 -- Find home or package module
159 findModule' dflags name = do
160 r <- findPackageModule' dflags name
162 Failed pkg_files -> do
163 j <- findHomeModule' dflags name
166 return (Failed (home_files ++ pkg_files))
168 -> return other_result
170 -> return other_result
172 findHomeModule' :: DynFlags -> Module -> IO LocalFindResult
173 findHomeModule' dflags mod = do
174 let home_path = importPaths dflags
179 [ ("hs", mkHomeModLocationSearched dflags mod "hs")
180 , ("lhs", mkHomeModLocationSearched dflags mod "lhs")
183 hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
184 , (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
187 -- In compilation manager modes, we look for source files in the home
188 -- package because we can compile these automatically. In one-shot
189 -- compilation mode we look for .hi and .hi-boot files only.
190 exts | isOneShot (ghcMode dflags) = hi_exts
191 | otherwise = source_exts
193 searchPathExts home_path mod exts
195 findPackageModule' :: DynFlags -> Module -> IO LocalFindResult
196 findPackageModule' dflags mod
197 = case moduleToPackageConfig dflags mod of
198 Nothing -> return (Failed [])
199 Just pkg_info -> findPackageIface dflags mod pkg_info
201 findPackageIface :: DynFlags -> Module -> (PackageConfig,Bool) -> IO LocalFindResult
202 findPackageIface dflags mod pkg_info@(pkg_conf, _) = do
204 tag = buildTag dflags
206 -- hi-suffix for packages depends on the build tag.
207 package_hisuf | null tag = "hi"
208 | otherwise = tag ++ "_hi"
211 mkPackageModLocation dflags pkg_info package_hisuf) ]
214 [ ("hs", mkPackageModLocation dflags pkg_info package_hisuf)
215 , ("lhs", mkPackageModLocation dflags pkg_info package_hisuf)
218 -- mkdependHS needs to look for source files in packages too, so
219 -- that we can make dependencies between package before they have
222 | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
223 | otherwise = hi_exts
224 -- we never look for a .hi-boot file in an external package;
225 -- .hi-boot files only make sense for the home package.
227 searchPathExts (importDirs pkg_conf) mod exts
229 -- -----------------------------------------------------------------------------
230 -- General path searching
233 :: [FilePath] -- paths to search
234 -> Module -- module name
237 FilePath -> BaseName -> IO FinderCacheEntry -- action
240 -> IO LocalFindResult
242 searchPathExts paths mod exts
243 = do result <- search to_search
245 hPutStrLn stderr (showSDoc $
246 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
247 , nest 2 (vcat (map text paths))
249 Succeeded (loc, p) -> text "Found" <+> ppr loc
250 Failed fs -> text "not found"])
255 basename = dots_to_slashes (moduleUserString mod)
257 to_search :: [(FilePath, IO FinderCacheEntry)]
258 to_search = [ (file, fn path basename)
261 let base | path == "." = basename
262 | otherwise = path ++ '/':basename
263 file = base ++ '.':ext
266 search [] = return (Failed (map fst to_search))
267 search ((file, mk_result) : rest) = do
268 b <- doesFileExist file
270 then do { res <- mk_result; return (Succeeded res) }
273 mkHomeModLocationSearched :: DynFlags -> Module -> FileExt
274 -> FilePath -> BaseName -> IO FinderCacheEntry
275 mkHomeModLocationSearched dflags mod suff path basename = do
276 loc <- mkHomeModLocation2 dflags mod (path ++ '/':basename) suff
277 return (loc, Nothing)
279 mkHiOnlyModLocation :: DynFlags -> FileExt -> FilePath -> BaseName
280 -> IO FinderCacheEntry
281 mkHiOnlyModLocation dflags hisuf path basename = do
282 loc <- hiOnlyModLocation dflags path basename hisuf
283 return (loc, Nothing)
285 mkPackageModLocation :: DynFlags -> (PackageConfig, Bool) -> FileExt
286 -> FilePath -> BaseName -> IO FinderCacheEntry
287 mkPackageModLocation dflags pkg_info hisuf path basename = do
288 loc <- hiOnlyModLocation dflags path basename hisuf
289 return (loc, Just pkg_info)
291 -- -----------------------------------------------------------------------------
292 -- Constructing a home module location
294 -- This is where we construct the ModLocation for a module in the home
295 -- package, for which we have a source file. It is called from three
298 -- (a) Here in the finder, when we are searching for a module to import,
299 -- using the search path (-i option).
301 -- (b) The compilation manager, when constructing the ModLocation for
302 -- a "root" module (a source file named explicitly on the command line
303 -- or in a :load command in GHCi).
305 -- (c) The driver in one-shot mode, when we need to construct a
306 -- ModLocation for a source file named on the command-line.
311 -- The name of the module
314 -- (a): The search path component where the source file was found.
318 -- (a): dots_to_slashes (moduleNameUserString mod)
319 -- (b) and (c): The filename of the source file, minus its extension
322 -- The filename extension of the source file (usually "hs" or "lhs").
324 mkHomeModLocation :: DynFlags -> Module -> FilePath -> IO ModLocation
325 mkHomeModLocation dflags mod src_filename = do
326 let (basename,extension) = splitFilename src_filename
327 mkHomeModLocation2 dflags mod basename extension
329 mkHomeModLocation2 :: DynFlags
331 -> FilePath -- Of source module, without suffix
334 mkHomeModLocation2 dflags mod src_basename ext = do
335 let mod_basename = dots_to_slashes (moduleUserString mod)
337 obj_fn <- mkObjPath dflags src_basename mod_basename
338 hi_fn <- mkHiPath dflags src_basename mod_basename
340 return (ModLocation{ ml_hs_file = Just (src_basename ++ '.':ext),
342 ml_obj_file = obj_fn })
344 hiOnlyModLocation :: DynFlags -> FilePath -> String -> Suffix -> IO ModLocation
345 hiOnlyModLocation dflags path basename hisuf
346 = do let full_basename = path++'/':basename
347 obj_fn <- mkObjPath dflags full_basename basename
348 return ModLocation{ ml_hs_file = Nothing,
349 ml_hi_file = full_basename ++ '.':hisuf,
350 -- Remove the .hi-boot suffix from
351 -- hi_file, if it had one. We always
352 -- want the name of the real .hi file
353 -- in the ml_hi_file field.
357 -- | Constructs the filename of a .o file for a given source file.
358 -- Does /not/ check whether the .o file exists
361 -> FilePath -- the filename of the source file, minus the extension
362 -> String -- the module name with dots replaced by slashes
364 mkObjPath dflags basename mod_basename
366 odir = outputDir dflags
367 osuf = objectSuf dflags
369 obj_basename | Just dir <- odir = dir ++ '/':mod_basename
370 | otherwise = basename
372 return (obj_basename ++ '.':osuf)
374 -- | Constructs the filename of a .hi file for a given source file.
375 -- Does /not/ check whether the .hi file exists
378 -> FilePath -- the filename of the source file, minus the extension
379 -> String -- the module name with dots replaced by slashes
381 mkHiPath dflags basename mod_basename
386 hi_basename | Just dir <- hidir = dir ++ '/':mod_basename
387 | otherwise = basename
389 return (hi_basename ++ '.':hisuf)
392 -- -----------------------------------------------------------------------------
393 -- findLinkable isn't related to the other stuff in here,
394 -- but there's no other obvious place for it
396 findLinkable :: Module -> ModLocation -> IO (Maybe Linkable)
397 findLinkable mod locn
398 = do let obj_fn = ml_obj_file locn
399 obj_exist <- doesFileExist obj_fn
403 do let stub_fn = case splitFilename3 obj_fn of
404 (dir, base, ext) -> dir ++ "/" ++ base ++ "_stub.o"
405 stub_exist <- doesFileExist stub_fn
406 obj_time <- getModificationTime obj_fn
408 then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
409 else return (Just (LM obj_time mod [DotO obj_fn]))
411 -- -----------------------------------------------------------------------------
414 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
417 -- -----------------------------------------------------------------------------
420 cantFindError :: DynFlags -> Module -> FindResult -> SDoc
421 cantFindError dflags mod_name find_result
422 = hang (ptext SLIT("Could not find module") <+> quotes (ppr mod_name) <> colon)
426 = case find_result of
428 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
429 <+> ptext SLIT("which is hidden")
432 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
437 -> ptext SLIT("it is not a module in the current program, or in any known package.")
438 | verbosity dflags < 3
439 -> ptext SLIT("use -v to see a list of the files searched for")
441 -> hang (ptext SLIT("locations searched:"))
442 2 (vcat (map text files))
444 Found _ _ -> panic "cantFindErr"