[project @ 2002-12-18 16:29:25 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / Finder.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[Finder]{Module Finder}
5
6 \begin{code}
7 module Finder (
8     flushFinderCache,   -- :: IO ()
9
10     findModule,         -- :: ModuleName -> IO (Maybe (Module, ModLocation))
11     findPackageModule,  -- :: ModuleName -> IO (Maybe (Module, ModLocation))
12
13     mkHomeModLocation,  -- :: ModuleName -> String -> FilePath 
14                         --      -> IO ModLocation
15
16     findLinkable,       -- :: ModuleName -> ModLocation -> IO (Maybe Linkable)
17
18     hiBootExt,          -- :: String
19     hiBootVerExt,       -- :: String
20
21   ) where
22
23 #include "HsVersions.h"
24
25 import Module
26 import UniqFM           ( filterUFM )
27 import Packages         ( PackageConfig(..) )
28 import HscTypes         ( Linkable(..), Unlinked(..) )
29 import DriverState
30 import DriverUtil       ( split_longest_prefix, splitFilename3 )
31 import FastString
32 import Config
33 import Util
34
35 import DATA_IOREF       ( IORef, writeIORef, readIORef )
36
37 import List
38 import Directory
39 import IO
40 import Monad
41
42 -- -----------------------------------------------------------------------------
43 -- The Finder
44
45 -- The Finder provides a thin filesystem abstraction to the rest of the
46 -- compiler.  For a given module, it knows (a) whether the module lives
47 -- in the home package or in another package, so it can make a Module
48 -- from a ModuleName, and (b) where the source, interface, and object
49 -- files for a module live.
50 -- 
51 -- It does *not* know which particular package a module lives in, because
52 -- that information is only contained in the interface file.
53
54 -- -----------------------------------------------------------------------------
55 -- The finder's cache
56
57 GLOBAL_VAR(finder_cache, emptyModuleEnv, ModuleEnv (Module,ModLocation))
58
59 -- remove all the home modules from the cache; package modules are
60 -- assumed to not move around during a session.
61 flushFinderCache :: IO ()
62 flushFinderCache = do
63   fm <- readIORef finder_cache
64   writeIORef finder_cache (filterUFM (not . isHomeModule . fst) fm)
65
66 addToFinderCache :: ModuleName -> (Module,ModLocation) -> IO ()
67 addToFinderCache mod_name stuff = do
68   fm <- readIORef finder_cache
69   writeIORef finder_cache (extendModuleEnvByName fm mod_name stuff)
70
71 lookupFinderCache :: ModuleName -> IO (Maybe (Module,ModLocation))
72 lookupFinderCache mod_name = do
73   fm <- readIORef finder_cache
74   return $! lookupModuleEnvByName fm mod_name
75
76 -- -----------------------------------------------------------------------------
77 -- Locating modules
78
79 -- This is the main interface to the finder, which maps ModuleNames to
80 -- Modules and ModLocations.
81 --
82 -- The Module contains one crucial bit of information about a module:
83 -- whether it lives in the current ("home") package or not (see Module
84 -- for more details).
85 --
86 -- The ModLocation contains the names of all the files associated with
87 -- that module: its source file, .hi file, object file, etc.
88
89 findModule :: ModuleName -> IO (Maybe (Module, ModLocation))
90 findModule name = do
91   r <- lookupFinderCache name
92   case r of
93    Just result -> return (Just result)
94    Nothing -> do  
95        j <- maybeHomeModule name
96        case j of
97          Just home_module -> return (Just home_module)
98          Nothing          -> findPackageMod name
99
100 findPackageModule :: ModuleName -> IO (Maybe (Module, ModLocation))
101 findPackageModule name = do
102   r <- lookupFinderCache name
103   case r of
104    Just result -> return (Just result)
105    Nothing     -> findPackageMod name
106
107 hiBootExt = "hi-boot"
108 hiBootVerExt = "hi-boot-" ++ cHscIfaceFileVersion
109
110 maybeHomeModule :: ModuleName -> IO (Maybe (Module, ModLocation))
111 maybeHomeModule mod_name = do
112    home_path <- readIORef v_Import_paths
113    hisuf     <- readIORef v_Hi_suf
114    mode      <- readIORef v_GhcMode
115
116    let
117      source_exts = 
118       [ ("hs",   mkHomeModLocation mod_name False)
119       , ("lhs",  mkHomeModLocation mod_name False)
120       ]
121      
122      hi_exts = [ (hisuf,  mkHiOnlyModLocation hisuf mod_name) ]
123      
124      boot_exts =
125        [ (hiBootVerExt, mkHiOnlyModLocation hisuf mod_name)
126        , (hiBootExt,    mkHiOnlyModLocation hisuf mod_name)
127        ]
128      
129         -- In compilation manager modes, we look for source files in the home
130         -- package because we can compile these automatically.  In one-shot
131         -- compilation mode we look for .hi and .hi-boot files only.
132         --
133         -- When generating dependencies, we're interested in either category.
134         --
135      exts
136          | mode == DoMkDependHS   = hi_exts ++ source_exts ++ boot_exts
137          | isCompManagerMode mode = source_exts
138          | otherwise {-one-shot-} = hi_exts ++ boot_exts
139
140    searchPathExts home_path mod_name exts
141         
142 -- -----------------------------------------------------------------------------
143 -- Looking for a package module
144
145 findPackageMod :: ModuleName -> IO (Maybe (Module, ModLocation))
146 findPackageMod mod_name = do
147   mode     <- readIORef v_GhcMode
148   imp_dirs <- getPackageImportPath -- including the 'auto' ones
149
150    -- hi-suffix for packages depends on the build tag.
151   package_hisuf <-
152         do tag <- readIORef v_Build_tag
153            if null tag
154                 then return "hi"
155                 else return (tag ++ "_hi")
156
157   let
158      hi_exts =
159         [ (package_hisuf, mkPackageModLocation package_hisuf mod_name) ]
160
161      source_exts = 
162        [ ("hs",   mkPackageModLocation package_hisuf mod_name)
163        , ("lhs",  mkPackageModLocation package_hisuf mod_name)
164        ]
165      
166      -- mkdependHS needs to look for source files in packages too, so
167      -- that we can make dependencies between package before they have
168      -- been built.
169      exts 
170       | mode == DoMkDependHS = hi_exts ++ source_exts
171       | otherwise = hi_exts
172
173       -- we never look for a .hi-boot file in an external package;
174       -- .hi-boot files only make sense for the home package.
175   searchPathExts imp_dirs mod_name exts
176
177 -- -----------------------------------------------------------------------------
178 -- General path searching
179
180 searchPathExts
181   :: [FilePath]         -- paths to search
182   -> ModuleName         -- module name
183   -> [ (
184         String,                                         -- suffix
185         String -> String -> String -> IO (Module, ModLocation)  -- action
186        )
187      ] 
188   -> IO (Maybe (Module, ModLocation))
189
190 searchPathExts path mod_name exts = search path
191   where
192     mod_str = moduleNameUserString mod_name
193     basename = map (\c -> if c == '.' then '/' else c) mod_str
194
195     search [] = return Nothing
196     search (p:ps) = loop exts
197       where     
198         base | p == "."  = basename
199              | otherwise = p ++ '/':basename
200
201         loop [] = search ps
202         loop ((ext,fn):exts) = do
203             let file = base ++ '.':ext
204             b <- doesFileExist file
205             if b then Just `liftM` fn p basename ext
206                  else loop exts
207
208 -- -----------------------------------------------------------------------------
209 -- Building ModLocations
210
211 mkHiOnlyModLocation hisuf mod_name path basename extension = do
212   addToFinderCache mod_name result
213   return result
214  where
215   result = ( mkHomeModule mod_name, hiOnlyModLocation path basename hisuf )
216
217 mkPackageModLocation hisuf mod_name path basename _extension = do
218   addToFinderCache mod_name result
219   return result
220  where
221   result = ( mkPackageModule mod_name, hiOnlyModLocation path basename hisuf )
222
223 hiOnlyModLocation path basename hisuf =
224       ModLocation{ ml_hspp_file = Nothing,
225                   ml_hs_file   = Nothing,
226                     -- remove the .hi-boot suffix from hi_file, if it
227                     -- had one.  We always want the name of the real
228                     -- .hi file in the ml_hi_file field.
229                   ml_hi_file   = path ++ '/':basename ++ '.':hisuf,
230                   ml_obj_file  = Nothing
231                  }
232
233 -- -----------------------------------------------------------------------------
234 -- Constructing a home module location
235
236 -- The .hi file always follows the module name, whereas the object
237 -- file may follow the name of the source file in the case where the
238 -- two differ (see summariseFile in compMan/CompManager.lhs).
239
240 -- The source filename is specified in three components.  For example,
241 -- if we have a module "A.B.C" which was found along the patch "/P/Q/R"
242 -- with extension ".hs", then the full filename is "/P/Q/R/A/B/C.hs".  The
243 -- components passed to mkHomeModLocation are
244 --
245 --   path:      "/P/Q/R"
246 --   basename:  "A/B/C"
247 --   extension: "hs"
248 --
249 -- the object file and interface file are constructed by possibly
250 -- replacing the path component with the values of the -odir or the
251 -- -hidr options respectively, and the extension with the values of
252 -- the -osuf and -hisuf options respectively.  That is, the basename
253 -- always remains intact.
254 --
255 -- mkHomeModLocation is called directly by the compilation manager to
256 -- construct the information for a root module.  For a "root" module,
257 -- the rules are slightly different. The filename is allowed to
258 -- diverge from the module name, but we have to name the interface
259 -- file after the module name.  For example, a root module
260 -- "/P/Q/R/foo.hs" will have components
261 --
262 --  path:       "/P/Q/R"
263 --  basename:   "foo"
264 --  extension:  "hs"
265 -- 
266 -- and we set the flag is_root to True, to indicate that the basename
267 -- portion for the .hi file should be replaced by the last component
268 -- of the module name.  eg. if the module name is "A.B.C" then basename
269 -- will be replaced by "C" for the .hi file only, resulting in an
270 -- .hi file like "/P/Q/R/C.hi" (subject to -hidir and -hisuf as usual).
271
272 mkHomeModLocation mod_name is_root path basename extension = do
273
274    hisuf  <- readIORef v_Hi_suf
275    hidir  <- readIORef v_Hi_dir
276    odir   <- readIORef v_Output_dir
277    osuf   <- readIORef v_Object_suf
278
279    let  -- hi filename
280        mod_str = moduleNameUserString mod_name
281        (_,mod_suf) = split_longest_prefix mod_str (=='.')
282
283        hi_basename
284           | is_root   = mod_suf
285           | otherwise = basename
286
287        hi_path | Just d <- hidir = d
288                | otherwise       = path
289        hi_fn = hi_path ++ '/':hi_basename ++ '.':hisuf
290
291         -- source filename (extension is always .hs or .lhs)
292        source_fn
293          | path == "."  = basename ++ '.':extension
294          | otherwise    = path ++ '/':basename ++ '.':extension
295
296         -- the object filename
297        obj_path | Just d <- odir = d
298                 | otherwise      = path
299        obj_fn = obj_path ++ '/':basename ++ '.':osuf
300
301   
302        result = ( mkHomeModule mod_name,
303                   ModLocation{ ml_hspp_file = Nothing,
304                                ml_hs_file   = Just source_fn,
305                                ml_hi_file   = hi_fn,
306                                ml_obj_file  = Just obj_fn,
307                        })
308
309    addToFinderCache mod_name result
310    return result
311
312 -- -----------------------------------------------------------------------------
313 -- findLinkable isn't related to the other stuff in here, 
314 -- but there' no other obvious place for it
315
316 findLinkable :: ModuleName -> ModLocation -> IO (Maybe Linkable)
317 findLinkable mod locn
318    | Just obj_fn <- ml_obj_file locn
319    = do obj_exist <- doesFileExist obj_fn
320         if not obj_exist 
321          then return Nothing 
322          else 
323          do let stub_fn = case splitFilename3 obj_fn of
324                              (dir, base, ext) -> dir ++ "/" ++ base ++ "_stub.o"
325             stub_exist <- doesFileExist stub_fn
326             obj_time <- getModificationTime obj_fn
327             if stub_exist
328              then return (Just (LM obj_time mod [DotO obj_fn, DotO stub_fn]))
329              else return (Just (LM obj_time mod [DotO obj_fn]))
330    | otherwise
331    = return Nothing
332 \end{code}