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