refactoring only: use the parameterised InstalledPackageInfo
[ghc-hetmet.git] / compiler / main / Finder.lhs
1 %
2 % (c) The University of Glasgow, 2000-2006
3 %
4 \section[Finder]{Module Finder}
5
6 \begin{code}
7 module Finder (
8     flushFinderCaches,
9     FindResult(..),
10     findImportedModule,
11     findExactModule,
12     findHomeModule,
13     mkHomeModLocation,
14     mkHomeModLocation2,
15     addHomeModuleToFinder,
16     uncacheModule,
17     mkStubPaths,
18
19     findObjectLinkableMaybe,
20     findObjectLinkable,
21
22     cannotFindModule,
23     cannotFindInterface,
24   ) where
25
26 #include "HsVersions.h"
27
28 import Module
29 import HscTypes
30 import Packages
31 import FastString
32 import Util
33 import PrelNames        ( gHC_PRIM )
34 import DynFlags         ( DynFlags(..), isOneShot, GhcMode(..) )
35 import Outputable
36 import FiniteMap
37 import UniqFM
38 import Maybes           ( expectJust )
39
40 import Data.IORef       ( IORef, writeIORef, readIORef, modifyIORef )
41 import Data.List
42 import System.Directory
43 import System.IO
44 import Control.Monad
45 import System.Time      ( ClockTime )
46
47
48 type FileExt = String   -- Filename extension
49 type BaseName = String  -- Basename of file
50
51 -- -----------------------------------------------------------------------------
52 -- The Finder
53
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.
57
58 -- It does *not* know which particular package a module lives in.  Use
59 -- Packages.lookupModuleInAllPackages for that.
60
61 -- -----------------------------------------------------------------------------
62 -- The finder's cache
63
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
70  where
71         this_pkg = thisPackage (hsc_dflags hsc_env)
72         fc_ref = hsc_FC hsc_env
73         mlc_ref = hsc_MLC hsc_env
74
75 flushModLocationCache :: PackageId -> IORef ModLocationCache -> IO ()
76 flushModLocationCache this_pkg ref = do
77   fm <- readIORef ref
78   writeIORef ref $! filterFM is_ext fm
79   return ()
80   where is_ext mod _ | modulePackageId mod /= this_pkg = True
81                      | otherwise = False
82
83 addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
84 addToFinderCache       ref key val = modifyIORef ref $ \c -> addToUFM c key val
85
86 addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
87 addToModLocationCache  ref key val = modifyIORef ref $ \c -> addToFM c key val
88
89 removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
90 removeFromFinderCache      ref key = modifyIORef ref $ \c -> delFromUFM c key
91
92 removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
93 removeFromModLocationCache ref key = modifyIORef ref $ \c -> delFromFM c key
94
95 lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
96 lookupFinderCache ref key = do 
97    c <- readIORef ref
98    return $! lookupUFM c key
99
100 lookupModLocationCache :: IORef ModLocationCache -> Module
101                        -> IO (Maybe ModLocation)
102 lookupModLocationCache ref key = do
103    c <- readIORef ref
104    return $! lookupFM c key
105
106 -- -----------------------------------------------------------------------------
107 -- The two external entry points
108
109 -- | Locate a module that was imported by the user.  We have the
110 -- module's name, and possibly a package name.  Without a package
111 -- name, this function will use the search path and the known exposed
112 -- packages to find the module, if a package is specified then only
113 -- that package is searched for the module.
114
115 findImportedModule :: HscEnv -> ModuleName -> Maybe PackageId -> IO FindResult
116 findImportedModule hsc_env mod_name mb_pkgid =
117   case mb_pkgid of
118         Nothing                    -> unqual_import
119         Just pkg | pkg == this_pkg -> home_import
120                  | otherwise       -> pkg_import pkg
121   where
122     dflags = hsc_dflags hsc_env
123     this_pkg = thisPackage dflags
124
125     home_import     = findHomeModule hsc_env mod_name
126
127     pkg_import pkg  = findPackageModule hsc_env (mkModule pkg mod_name)
128                         -- ToDo: this isn't quite right, the module we want
129                         -- might actually be in another package, but re-exposed
130                         -- ToDo: should return NotFoundInPackage if
131                         -- the module isn't exposed by the package.
132
133     unqual_import   = home_import 
134                         `orIfNotFound`
135                       findExposedPackageModule hsc_env mod_name
136
137 -- | Locate a specific 'Module'.  The purpose of this function is to
138 -- create a 'ModLocation' for a given 'Module', that is to find out
139 -- where the files associated with this module live.  It is used when
140 -- reading the interface for a module mentioned by another interface, 
141 -- for example (a "system import").
142
143 findExactModule :: HscEnv -> Module -> IO FindResult
144 findExactModule hsc_env mod =
145    let dflags = hsc_dflags hsc_env in
146    if modulePackageId mod == thisPackage dflags
147         then findHomeModule hsc_env (moduleName mod)
148         else findPackageModule hsc_env mod
149
150 -- -----------------------------------------------------------------------------
151 -- Helpers
152
153 orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
154 this `orIfNotFound` or_this = do
155   res <- this
156   case res of
157     NotFound here _ -> do
158         res2 <- or_this
159         case res2 of
160            NotFound or_here pkg -> return (NotFound (here ++ or_here) pkg)
161            _other -> return res2
162     _other -> return res
163
164
165 homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
166 homeSearchCache hsc_env mod_name do_this = do
167   m <- lookupFinderCache (hsc_FC hsc_env) mod_name
168   case m of 
169     Just result -> return result
170     Nothing     -> do
171         result <- do_this
172         addToFinderCache (hsc_FC hsc_env) mod_name result
173         case result of
174            Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
175            _other        -> return ()
176         return result
177
178 findExposedPackageModule :: HscEnv -> ModuleName -> IO FindResult
179 findExposedPackageModule hsc_env mod_name
180         -- not found in any package:
181   | null found = return (NotFound [] Nothing)
182         -- found in just one exposed package:
183   | [(pkg_conf, _)] <- found_exposed
184         = let pkgid = mkPackageId (package pkg_conf) in      
185           findPackageModule_ hsc_env (mkModule pkgid mod_name) pkg_conf
186         -- not found in any exposed package, report how it was hidden:
187   | null found_exposed, ((pkg_conf, exposed_mod):_) <- found
188         = let pkgid = mkPackageId (package pkg_conf) in
189           if not (exposed_mod)
190                 then return (ModuleHidden pkgid)
191                 else return (PackageHidden pkgid)
192   | otherwise
193         = return (FoundMultiple (map (mkPackageId.package.fst) found_exposed))
194   where
195         dflags = hsc_dflags hsc_env
196         found = lookupModuleInAllPackages dflags mod_name
197         found_exposed = filter is_exposed found
198         is_exposed (pkg_conf,exposed_mod) = exposed pkg_conf && exposed_mod
199
200
201 modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
202 modLocationCache hsc_env mod do_this = do
203   mb_loc <- lookupModLocationCache mlc mod
204   case mb_loc of
205      Just loc -> return (Found loc mod)
206      Nothing  -> do
207         result <- do_this
208         case result of
209             Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
210             _other -> return ()
211         return result
212   where
213     mlc = hsc_MLC hsc_env
214
215 addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
216 addHomeModuleToFinder hsc_env mod_name loc = do
217   let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
218   addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
219   addToModLocationCache (hsc_MLC hsc_env) mod loc
220   return mod
221
222 uncacheModule :: HscEnv -> ModuleName -> IO ()
223 uncacheModule hsc_env mod = do
224   let this_pkg = thisPackage (hsc_dflags hsc_env)
225   removeFromFinderCache (hsc_FC hsc_env) mod
226   removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
227
228 -- -----------------------------------------------------------------------------
229 --      The internal workers
230
231 -- | Search for a module in the home package only.
232 findHomeModule :: HscEnv -> ModuleName -> IO FindResult
233 findHomeModule hsc_env mod_name =
234    homeSearchCache hsc_env mod_name $
235    let 
236      dflags = hsc_dflags hsc_env
237      home_path = importPaths dflags
238      hisuf = hiSuf dflags
239      mod = mkModule (thisPackage dflags) mod_name
240
241      source_exts = 
242       [ ("hs",   mkHomeModLocationSearched dflags mod_name "hs")
243       , ("lhs",  mkHomeModLocationSearched dflags mod_name "lhs")
244       ]
245      
246      hi_exts = [ (hisuf,                mkHiOnlyModLocation dflags hisuf)
247                , (addBootSuffix hisuf,  mkHiOnlyModLocation dflags hisuf)
248                ]
249      
250         -- In compilation manager modes, we look for source files in the home
251         -- package because we can compile these automatically.  In one-shot
252         -- compilation mode we look for .hi and .hi-boot files only.
253      exts | isOneShot (ghcMode dflags) = hi_exts
254           | otherwise                  = source_exts
255    in
256
257   -- special case for GHC.Prim; we won't find it in the filesystem.
258   -- This is important only when compiling the base package (where GHC.Prim
259   -- is a home module).
260   if mod == gHC_PRIM 
261         then return (Found (error "GHC.Prim ModLocation") mod)
262         else 
263
264    searchPathExts home_path mod exts
265
266
267 -- | Search for a module in external packages only.
268 findPackageModule :: HscEnv -> Module -> IO FindResult
269 findPackageModule hsc_env mod = do
270   let
271         dflags = hsc_dflags hsc_env
272         pkg_id = modulePackageId mod
273         pkg_map = pkgIdMap (pkgState dflags)
274   --
275   case lookupPackage pkg_map pkg_id of
276      Nothing -> return (NoPackage pkg_id)
277      Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
278       
279 findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
280 findPackageModule_ hsc_env mod pkg_conf = 
281   modLocationCache hsc_env mod $
282
283   -- special case for GHC.Prim; we won't find it in the filesystem.
284   if mod == gHC_PRIM 
285         then return (Found (error "GHC.Prim ModLocation") mod)
286         else 
287
288   let
289      dflags = hsc_dflags hsc_env
290      tag = buildTag dflags
291
292            -- hi-suffix for packages depends on the build tag.
293      package_hisuf | null tag  = "hi"
294                    | otherwise = tag ++ "_hi"
295      hi_exts =
296         [ (package_hisuf, mkHiOnlyModLocation dflags package_hisuf) ]
297
298      source_exts = 
299        [ ("hs",   mkHiOnlyModLocation dflags package_hisuf)
300        , ("lhs",  mkHiOnlyModLocation dflags package_hisuf)
301        ]
302
303      -- mkdependHS needs to look for source files in packages too, so
304      -- that we can make dependencies between package before they have
305      -- been built.
306      exts 
307       | MkDepend <- ghcMode dflags = hi_exts ++ source_exts
308       | otherwise                  = hi_exts
309       -- we never look for a .hi-boot file in an external package;
310       -- .hi-boot files only make sense for the home package.
311   in
312   searchPathExts (importDirs pkg_conf) mod exts
313
314 -- -----------------------------------------------------------------------------
315 -- General path searching
316
317 searchPathExts
318   :: [FilePath]         -- paths to search
319   -> Module             -- module name
320   -> [ (
321         FileExt,                                -- suffix
322         FilePath -> BaseName -> IO ModLocation  -- action
323        )
324      ] 
325   -> IO FindResult
326
327 searchPathExts paths mod exts 
328    = do result <- search to_search
329 {-
330         hPutStrLn stderr (showSDoc $
331                 vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
332                     , nest 2 (vcat (map text paths))
333                     , case result of
334                         Succeeded (loc, p) -> text "Found" <+> ppr loc
335                         Failed fs          -> text "not found"])
336 -}      
337         return result
338
339   where
340     basename = dots_to_slashes (moduleNameString (moduleName mod))
341
342     to_search :: [(FilePath, IO ModLocation)]
343     to_search = [ (file, fn path basename)
344                 | path <- paths, 
345                   (ext,fn) <- exts,
346                   let base | path == "." = basename
347                            | otherwise   = path `joinFileName` basename
348                       file = base `joinFileExt` ext
349                 ]
350
351     search [] = return (NotFound (map fst to_search) (Just (modulePackageId mod)))
352     search ((file, mk_result) : rest) = do
353       b <- doesFileExist file
354       if b 
355         then do { loc <- mk_result; return (Found loc mod) }
356         else search rest
357
358 mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
359                           -> FilePath -> BaseName -> IO ModLocation
360 mkHomeModLocationSearched dflags mod suff path basename = do
361    mkHomeModLocation2 dflags mod (path `joinFileName` basename) suff
362
363 -- -----------------------------------------------------------------------------
364 -- Constructing a home module location
365
366 -- This is where we construct the ModLocation for a module in the home
367 -- package, for which we have a source file.  It is called from three
368 -- places:
369 --
370 --  (a) Here in the finder, when we are searching for a module to import,
371 --      using the search path (-i option).
372 --
373 --  (b) The compilation manager, when constructing the ModLocation for
374 --      a "root" module (a source file named explicitly on the command line
375 --      or in a :load command in GHCi).
376 --
377 --  (c) The driver in one-shot mode, when we need to construct a
378 --      ModLocation for a source file named on the command-line.
379 --
380 -- Parameters are:
381 --
382 -- mod
383 --      The name of the module
384 --
385 -- path
386 --      (a): The search path component where the source file was found.
387 --      (b) and (c): "."
388 --
389 -- src_basename
390 --      (a): dots_to_slashes (moduleNameUserString mod)
391 --      (b) and (c): The filename of the source file, minus its extension
392 --
393 -- ext
394 --      The filename extension of the source file (usually "hs" or "lhs").
395
396 mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
397 mkHomeModLocation dflags mod src_filename = do
398    let (basename,extension) = splitFilename src_filename
399    mkHomeModLocation2 dflags mod basename extension
400
401 mkHomeModLocation2 :: DynFlags
402                    -> ModuleName
403                    -> FilePath  -- Of source module, without suffix
404                    -> String    -- Suffix
405                    -> IO ModLocation
406 mkHomeModLocation2 dflags mod src_basename ext = do
407    let mod_basename = dots_to_slashes (moduleNameString mod)
408
409    obj_fn  <- mkObjPath  dflags src_basename mod_basename
410    hi_fn   <- mkHiPath   dflags src_basename mod_basename
411
412    return (ModLocation{ ml_hs_file   = Just (src_basename `joinFileExt` ext),
413                         ml_hi_file   = hi_fn,
414                         ml_obj_file  = obj_fn })
415
416 mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
417                     -> IO ModLocation
418 mkHiOnlyModLocation dflags hisuf path basename
419  = do let full_basename = path `joinFileName` basename
420       obj_fn  <- mkObjPath  dflags full_basename basename
421       return ModLocation{    ml_hs_file   = Nothing,
422                              ml_hi_file   = full_basename  `joinFileExt` hisuf,
423                                 -- Remove the .hi-boot suffix from
424                                 -- hi_file, if it had one.  We always
425                                 -- want the name of the real .hi file
426                                 -- in the ml_hi_file field.
427                              ml_obj_file  = obj_fn
428                   }
429
430 -- | Constructs the filename of a .o file for a given source file.
431 -- Does /not/ check whether the .o file exists
432 mkObjPath
433   :: DynFlags
434   -> FilePath           -- the filename of the source file, minus the extension
435   -> String             -- the module name with dots replaced by slashes
436   -> IO FilePath
437 mkObjPath dflags basename mod_basename
438   = do  let
439                 odir = objectDir dflags
440                 osuf = objectSuf dflags
441         
442                 obj_basename | Just dir <- odir = dir `joinFileName` mod_basename
443                              | otherwise        = basename
444
445         return (obj_basename `joinFileExt` osuf)
446
447 -- | Constructs the filename of a .hi file for a given source file.
448 -- Does /not/ check whether the .hi file exists
449 mkHiPath
450   :: DynFlags
451   -> FilePath           -- the filename of the source file, minus the extension
452   -> String             -- the module name with dots replaced by slashes
453   -> IO FilePath
454 mkHiPath dflags basename mod_basename
455   = do  let
456                 hidir = hiDir dflags
457                 hisuf = hiSuf dflags
458
459                 hi_basename | Just dir <- hidir = dir `joinFileName` mod_basename
460                             | otherwise         = basename
461
462         return (hi_basename `joinFileExt` hisuf)
463
464
465 -- -----------------------------------------------------------------------------
466 -- Filenames of the stub files
467
468 -- We don't have to store these in ModLocations, because they can be derived
469 -- from other available information, and they're only rarely needed.
470
471 mkStubPaths
472   :: DynFlags
473   -> ModuleName
474   -> ModLocation
475   -> (FilePath,FilePath,FilePath)
476
477 mkStubPaths dflags mod location
478   = let
479                 stubdir = stubDir dflags
480
481                 mod_basename = dots_to_slashes (moduleNameString mod)
482                 src_basename = basenameOf (expectJust "mkStubPaths" 
483                                                 (ml_hs_file location))
484
485                 stub_basename0
486                         | Just dir <- stubdir = dir `joinFileName` mod_basename
487                         | otherwise           = src_basename
488
489                 stub_basename = stub_basename0 ++ "_stub"
490
491                 -- this is the filename we're going to use when
492                 -- #including the stub_h file from the .hc file.
493                 -- Without -stubdir, we just #include the basename
494                 -- (eg. for a module A.B, we #include "B_stub.h"),
495                 -- relying on the fact that we add an implicit -I flag
496                 -- for the directory in which the source file resides
497                 -- (see DriverPipeline.hs).  With -stubdir, we
498                 -- #include "A/B.h", assuming that the user has added
499                 -- -I<dir> along with -stubdir <dir>.
500                 include_basename
501                         | Just _ <- stubdir = mod_basename 
502                         | otherwise         = filenameOf src_basename
503      in
504         (stub_basename `joinFileExt` "c",
505          stub_basename `joinFileExt` "h",
506          (include_basename ++ "_stub") `joinFileExt` "h")
507         -- the _stub.o filename is derived from the ml_obj_file.
508
509 -- -----------------------------------------------------------------------------
510 -- findLinkable isn't related to the other stuff in here, 
511 -- but there's no other obvious place for it
512
513 findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
514 findObjectLinkableMaybe mod locn
515    = do let obj_fn = ml_obj_file locn
516         maybe_obj_time <- modificationTimeIfExists obj_fn
517         case maybe_obj_time of
518           Nothing -> return Nothing
519           Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
520
521 -- Make an object linkable when we know the object file exists, and we know
522 -- its modification time.
523 findObjectLinkable :: Module -> FilePath -> ClockTime -> IO Linkable
524 findObjectLinkable mod obj_fn obj_time = do
525   let stub_fn = case splitFilename3 obj_fn of
526                         (dir, base, _ext) -> dir ++ "/" ++ base ++ "_stub.o"
527   stub_exist <- doesFileExist stub_fn
528   if stub_exist
529         then return (LM obj_time mod [DotO obj_fn, DotO stub_fn])
530         else return (LM obj_time mod [DotO obj_fn])
531
532 -- -----------------------------------------------------------------------------
533 -- Utils
534
535 dots_to_slashes :: String -> String
536 dots_to_slashes = map (\c -> if c == '.' then '/' else c)
537
538 -- -----------------------------------------------------------------------------
539 -- Error messages
540
541 cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
542 cannotFindModule = cantFindErr SLIT("Could not find module")
543
544 cannotFindInterface  :: DynFlags -> ModuleName -> FindResult -> SDoc
545 cannotFindInterface = cantFindErr SLIT("Failed to load interface for")
546
547 cantFindErr :: LitString -> DynFlags -> ModuleName -> FindResult -> SDoc
548 cantFindErr cannot_find _dflags mod_name (FoundMultiple pkgs)
549   = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon) 2 (
550        sep [ptext SLIT("it was found in multiple packages:"),
551                 hsep (map (text.packageIdString) pkgs)]
552     )
553 cantFindErr cannot_find dflags mod_name find_result
554   = hang (ptext cannot_find <+> quotes (ppr mod_name) <> colon)
555        2 more_info
556   where
557     more_info
558       = case find_result of
559             PackageHidden pkg 
560                 -> ptext SLIT("it is a member of package") <+> ppr pkg <> comma
561                    <+> ptext SLIT("which is hidden")
562
563             ModuleHidden pkg
564                 -> ptext SLIT("it is hidden") <+> parens (ptext SLIT("in package")
565                    <+> ppr pkg)
566
567             NoPackage pkg
568                 -> ptext SLIT("no package matching") <+> ppr pkg <+>
569                    ptext SLIT("was found")
570
571             NotFound files mb_pkg
572                 | null files
573                 -> ptext SLIT("it is not a module in the current program, or in any known package.")
574                 | Just pkg <- mb_pkg, pkg /= thisPackage dflags, build_tag /= ""
575                 -> let 
576                      build = if build_tag == "p" then "profiling" 
577                                                  else "\"" ++ build_tag ++ "\""
578                    in
579                    ptext SLIT("Perhaps you haven't installed the ") <> text build <>
580                    ptext SLIT(" libraries for package ") <> ppr pkg <> char '?' $$
581                    not_found files
582
583                 | otherwise
584                 -> not_found files
585
586             NotFoundInPackage pkg
587                 -> ptext SLIT("it is not in package") <+> ppr pkg
588
589             _ -> panic "cantFindErr"
590
591     build_tag = buildTag dflags
592
593     not_found files
594         | verbosity dflags < 3
595         = ptext SLIT("Use -v to see a list of the files searched for.")
596         | otherwise 
597         = hang (ptext SLIT("locations searched:")) 2 (vcat (map text files))
598 \end{code}