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