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