[project @ 1996-12-19 09:10:02 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnIfaces.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module RnIfaces (
10         getInterfaceExports,
11         getImportedInstDecls,
12         getSpecialInstModules,
13         getDecl, getWiredInDecl,
14         getImportVersions,
15
16         checkUpToDate,
17
18         getDeclBinders,
19         mkSearchPath
20     ) where
21
22 IMP_Ubiq()
23
24
25 import HsSyn            ( HsDecl(..), TyDecl(..), ClassDecl(..), HsTyVar, Bind, HsExpr, Sig(..), 
26                           HsBinds(..), MonoBinds, DefaultDecl, ConDecl(..), HsType, BangType, IfaceSig(..),
27                           FixityDecl(..), Fixity, Fake, InPat, InstDecl(..), SYN_IE(Version), HsIdInfo
28                         )
29 import HsPragmas        ( noGenPragmas )
30 import RdrHsSyn         ( SYN_IE(RdrNameHsDecl), SYN_IE(RdrNameInstDecl), 
31                           RdrName, rdrNameOcc
32                         )
33 import RnEnv            ( newGlobalName, lookupRn, addImplicitOccsRn, availNames )
34 import RnSource         ( rnHsType )
35 import RnMonad
36 import ParseIface       ( parseIface )
37
38 import ErrUtils         ( SYN_IE(Error), SYN_IE(Warning) )
39 import FiniteMap        ( FiniteMap, emptyFM, unitFM, lookupFM, addToFM, addListToFM, fmToList )
40 import Name             ( Name {-instance NamedThing-}, Provenance, OccName(..),
41                           modAndOcc, occNameString, moduleString, pprModule,
42                           NameSet(..), emptyNameSet, unionNameSets, nameSetToList,
43                           minusNameSet, mkNameSet,
44                           isWiredInName, maybeWiredInTyConName, maybeWiredInIdName
45                          )
46 import Id               ( GenId, Id(..), idType, dataConTyCon, isDataCon )
47 import TyCon            ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
48 import Type             ( namesOfType )
49 import TyVar            ( GenTyVar )
50 import SrcLoc           ( mkIfaceSrcLoc )
51 import PrelMods         ( gHC__ )
52 import Bag
53 import Maybes           ( MaybeErr(..), expectJust, maybeToBool )
54 import ListSetOps       ( unionLists )
55 import Pretty
56 import PprStyle         ( PprStyle(..) )
57 import Util             ( pprPanic )
58 \end{code}
59
60
61
62 %*********************************************************
63 %*                                                      *
64 \subsection{Loading a new interface file}
65 %*                                                      *
66 %*********************************************************
67
68 \begin{code}
69 loadInterface :: Pretty -> Module -> RnMG Ifaces
70 loadInterface doc_str load_mod 
71   = getIfacesRn                 `thenRn` \ ifaces ->
72     let
73         Ifaces this_mod mod_vers_map export_env_map vers_map decls_map inst_map inst_mods = ifaces
74     in
75         -- CHECK WHETHER WE HAVE IT ALREADY
76     if maybeToBool (lookupFM export_env_map load_mod) 
77     then
78         returnRn ifaces         -- Already in the cache; don't re-read it
79     else
80
81         -- READ THE MODULE IN
82     findAndReadIface doc_str load_mod           `thenRn` \ read_result ->
83     case read_result of {
84         -- Check for not found
85         Nothing ->      -- Not found, so add an empty export env to the Ifaces map
86                         -- so that we don't look again
87                    let
88                         new_export_env_map = addToFM export_env_map load_mod ([],[])
89                         new_ifaces = Ifaces this_mod mod_vers_map 
90                                             new_export_env_map 
91                                             vers_map decls_map inst_map inst_mods
92                    in
93                    setIfacesRn new_ifaces               `thenRn_`
94                    failWithRn new_ifaces (noIfaceErr load_mod) ;
95
96         -- Found and parsed!
97         Just (ParsedIface _ mod_vers usages exports rd_inst_mods fixs decls insts) ->
98
99         -- LOAD IT INTO Ifaces
100     mapRn loadExport exports                                    `thenRn` \ avails ->
101     foldlRn (loadDecl load_mod) (decls_map,vers_map) decls      `thenRn` \ (new_decls_map, new_vers_map) ->
102     foldlRn (loadInstDecl load_mod) inst_map insts              `thenRn` \ new_insts_map ->
103     let
104          export_env = (avails, fixs)
105
106                         -- Exclude this module from the "special-inst" modules
107          new_inst_mods = inst_mods `unionLists` (filter (/= this_mod) rd_inst_mods)
108
109          new_ifaces = Ifaces this_mod
110                              (addToFM mod_vers_map load_mod mod_vers)
111                              (addToFM export_env_map load_mod export_env)
112                              new_vers_map
113                              new_decls_map
114                              new_insts_map
115                              new_inst_mods 
116     in
117     setIfacesRn new_ifaces              `thenRn_`
118     returnRn new_ifaces
119     }
120
121 loadExport :: ExportItem -> RnMG AvailInfo
122 loadExport (mod, occ, occs)
123   = new_name occ                `thenRn` \ name ->
124     mapRn new_name occs         `thenRn` \ names ->
125     returnRn (Avail name names)
126   where
127     new_name occ = newGlobalName mod occ
128
129 loadVersion :: Module -> VersionMap -> (OccName,Version) -> RnMG VersionMap
130 loadVersion mod vers_map (occ, version)
131   = newGlobalName mod occ                       `thenRn` \ name ->
132     returnRn (addToFM vers_map name version)
133
134
135 loadDecl :: Module -> (DeclsMap, VersionMap)
136          -> (Version, RdrNameHsDecl)
137          -> RnMG (DeclsMap, VersionMap)
138 loadDecl mod (decls_map, vers_map) (version, decl)
139   = getDeclBinders new_implicit_name decl       `thenRn` \ avail@(Avail name _) ->
140     returnRn (addListToFM decls_map
141                           [(name,(avail,decl)) | name <- availNames avail],
142               addToFM vers_map name version
143     )
144   where
145     new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
146
147 loadInstDecl :: Module -> Bag IfaceInst -> RdrNameInstDecl -> RnMG (Bag IfaceInst)
148 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
149   = initRnMS emptyRnEnv mod_name InterfaceMode $
150
151         -- Find out what type constructors and classes are mentioned in the
152         -- instance declaration.  We have to be a bit clever.
153         --
154         -- We want to rename the type so that we can find what
155         -- (free) type constructors are inside it.  But we must *not* thereby
156         -- put new occurrences into the global pool because otherwise we'll force
157         -- them all to be loaded.  We kill two birds with ones stone by renaming
158         -- with a fresh occurrence pool.
159     findOccurrencesRn (rnHsType inst_ty)        `thenRn` \ ty_names ->
160
161     returnRn ((ty_names, mod_name, decl) `consBag` insts)
162 \end{code}
163
164
165 %********************************************************
166 %*                                                      *
167 \subsection{Loading usage information}
168 %*                                                      *
169 %********************************************************
170
171 \begin{code}
172 checkUpToDate :: Module -> RnMG Bool            -- True <=> no need to recompile
173 checkUpToDate mod_name
174   = findAndReadIface doc_str mod_name           `thenRn` \ read_result ->
175     case read_result of
176         Nothing ->      -- Old interface file not found, so we'd better bale out
177                     traceRn (ppSep [ppStr "Didnt find old iface", pprModule PprDebug mod_name]) `thenRn_`
178                     returnRn False
179
180         Just (ParsedIface _ _ usages _ _ _ _ _) 
181                 ->      -- Found it, so now check it
182                     checkModUsage usages
183   where
184         -- Only look in current directory, with suffix .hi
185     doc_str = ppSep [ppStr "Need usage info from", pprModule PprDebug mod_name]
186
187
188 checkModUsage [] = returnRn True                -- Yes!  Everything is up to date!
189
190 checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
191   = loadInterface doc_str mod           `thenRn` \ ifaces ->
192     let
193         Ifaces _ mod_vers_map _ new_vers_map _ _ _ = ifaces
194         maybe_new_mod_vers = lookupFM mod_vers_map mod
195         Just new_mod_vers  = maybe_new_mod_vers
196     in
197         -- If we can't find a version number for the old module then
198         -- bale out saying things aren't up to date
199     if not (maybeToBool maybe_new_mod_vers) then
200         returnRn False
201     else
202
203         -- If the module version hasn't changed, just move on
204     if new_mod_vers == old_mod_vers then
205         traceRn (ppSep [ppStr "Module version unchanged:", pprModule PprDebug mod])     `thenRn_`
206         checkModUsage rest
207     else
208     traceRn (ppSep [ppStr "Module version has changed:", pprModule PprDebug mod])       `thenRn_`
209
210         -- New module version, so check entities inside
211     checkEntityUsage mod new_vers_map old_local_vers    `thenRn` \ up_to_date ->
212     if up_to_date then
213         traceRn (ppStr "...but the bits I use havn't.") `thenRn_`
214         checkModUsage rest      -- This one's ok, so check the rest
215     else
216         returnRn False          -- This one failed, so just bail out now
217   where
218     doc_str = ppSep [ppStr "need version info for", pprModule PprDebug mod]
219
220
221 checkEntityUsage mod new_vers_map [] 
222   = returnRn True       -- Yes!  All up to date!
223
224 checkEntityUsage mod new_vers_map ((occ_name,old_vers) : rest)
225   = newGlobalName mod occ_name          `thenRn` \ name ->
226     case lookupFM new_vers_map name of
227
228         Nothing       ->        -- We used it before, but it ain't there now
229                           traceRn (ppSep [ppStr "...and this no longer exported:", ppr PprDebug name])  `thenRn_`
230                           returnRn False
231
232         Just new_vers ->        -- It's there, but is it up to date?
233                           if new_vers == old_vers then
234                                 -- Up to date, so check the rest
235                                 checkEntityUsage mod new_vers_map rest
236                           else
237                                 traceRn (ppSep [ppStr "...and this is out of date:", ppr PprDebug name])  `thenRn_`
238                                 returnRn False  -- Out of date, so bale out
239 \end{code}
240
241
242 %*********************************************************
243 %*                                                      *
244 \subsection{Getting in a declaration}
245 %*                                                      *
246 %*********************************************************
247
248 \begin{code}
249 getDecl :: Name -> RnMG (AvailInfo, RdrNameHsDecl)
250 getDecl name
251   = traceRn doc_str                     `thenRn_`
252     loadInterface doc_str mod           `thenRn` \ (Ifaces _ _ _ _ decls_map _ _) ->
253     case lookupFM decls_map name of
254
255       Just avail_w_decl -> returnRn avail_w_decl
256
257       Nothing           ->      -- Can happen legitimately for "Optional" occurrences
258                            returnRn (NotAvailable, ValD EmptyBinds)
259   where
260      (mod,_) = modAndOcc name
261      doc_str = ppSep [ppStr "Need decl for", ppr PprDebug name]
262 \end{code}
263
264 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
265 It behaves exactly as if the wired in decl were actually in an interface file.
266 Specifically,
267   *     if the wired-in name is a data type constructor or a data constructor, 
268         it brings in the type constructor and all the data constructors; and
269         marks as "occurrences" any free vars of the data con.
270
271   *     similarly for synonum type constructor
272
273   *     if the wired-in name is another wired-in Id, it marks as "occurrences"
274         the free vars of the Id's type.
275
276   *     it loads the interface file for the wired-in thing for the
277         sole purpose of making sure that its instance declarations are available
278
279 All this is necessary so that we know all types that are "in play", so
280 that we know just what instances to bring into scope.
281         
282 \begin{code}
283 getWiredInDecl :: Name -> RnMG AvailInfo
284 getWiredInDecl name
285   =     -- Force in the home module in case it has instance decls for
286         -- the thing we are interested in
287     (if mod == gHC__ then
288         returnRn ()                     -- Mini hack; GHC is guaranteed not to have
289                                         -- instance decls, so it's a waste of time
290                                         -- to read it
291     else
292         loadInterface doc_str mod       `thenRn_`
293         returnRn ()
294     )                                           `thenRn_`
295
296     if (maybeToBool maybe_wired_in_tycon) then
297         get_wired_tycon the_tycon
298     else                                -- Must be a wired-in-Id
299     if (isDataCon the_id) then          -- ... a wired-in data constructor
300         get_wired_tycon (dataConTyCon the_id)
301     else                                -- ... a wired-in non data-constructor
302         get_wired_id the_id
303   where
304     doc_str = ppSep [ppStr "Need home module for wired in thing", ppr PprDebug name]
305     (mod,_) = modAndOcc name
306     maybe_wired_in_tycon = maybeWiredInTyConName name
307     maybe_wired_in_id    = maybeWiredInIdName    name
308     Just the_tycon       = maybe_wired_in_tycon
309     Just the_id          = maybe_wired_in_id
310
311 get_wired_id id
312   = addImplicitOccsRn (nameSetToList id_mentioned)      `thenRn_`
313     returnRn (Avail (getName id) [])
314   where
315     id_mentioned         = namesOfType (idType id)
316
317 get_wired_tycon tycon 
318   | isSynTyCon tycon
319   = addImplicitOccsRn (nameSetToList mentioned)         `thenRn_`
320     returnRn (Avail (getName tycon) [])
321   where
322     (tyvars,ty) = getSynTyConDefn tycon
323     mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
324
325 get_wired_tycon tycon 
326   | otherwise           -- data or newtype
327   = addImplicitOccsRn (nameSetToList mentioned)         `thenRn_`
328     returnRn (Avail (getName tycon) (map getName data_cons))
329   where
330     data_cons = tyConDataCons tycon
331     mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
332 \end{code}
333
334
335 %*********************************************************
336 %*                                                      *
337 \subsection{Getting other stuff}
338 %*                                                      *
339 %*********************************************************
340
341 \begin{code}
342 getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
343 getInterfaceExports mod
344   = loadInterface doc_str mod           `thenRn` \ (Ifaces _ _ export_envs _ _ _ _) ->
345     case lookupFM export_envs mod of
346         Nothing ->      -- Not there; it must be that the interface file wasn't found;
347                         -- the error will have been reported already.
348                         -- (Actually loadInterface should put the empty export env in there
349                         --  anyway, but this does no harm.)
350                       returnRn ([],[])
351
352         Just stuff -> returnRn stuff
353   where
354     doc_str = ppSep [pprModule PprDebug mod, ppStr "is directly imported"]
355
356
357 getImportedInstDecls :: RnMG [IfaceInst]
358 getImportedInstDecls
359   =     -- First load any special-instance modules that aren't aready loaded
360     getSpecialInstModules                       `thenRn` \ inst_mods ->
361     mapRn load_it inst_mods                     `thenRn_`
362
363         -- Now we're ready to grab the instance declarations
364     getIfacesRn                                         `thenRn` \ ifaces ->
365     let
366          Ifaces _ _ _ _ _ insts _ = ifaces
367     in
368     returnRn (bagToList insts) 
369   where
370     load_it mod = loadInterface (doc_str mod) mod
371     doc_str mod = ppSep [pprModule PprDebug mod, ppStr "is a special-instance module"]
372
373 getSpecialInstModules :: RnMG [Module]
374 getSpecialInstModules 
375   = getIfacesRn                                         `thenRn` \ ifaces ->
376     let
377          Ifaces _ _ _ _ _ _ inst_mods = ifaces
378     in
379     returnRn inst_mods
380 \end{code}
381
382 \begin{code}
383 getImportVersions :: [AvailInfo]                        -- Imported avails
384                   -> RnMG (VersionInfo Name)    -- Version info for these names
385
386 getImportVersions imported_avails       
387   = getIfacesRn                                 `thenRn` \ ifaces ->
388     let
389          Ifaces _ mod_versions_map _ version_map _ _ _ = ifaces
390
391          -- import_versions is harder: we have to group together all the things imported
392          -- from a particular module.  We do this with yet another finite map
393
394          mv_map :: FiniteMap Module [LocalVersion Name]
395          mv_map            = foldl add_mv emptyFM imported_avails
396          add_mv mv_map (Avail name _) 
397             | isWiredInName name = mv_map       -- Don't record versions for wired-in names
398             | otherwise = case lookupFM mv_map mod of
399                                 Just versions -> addToFM mv_map mod ((name,version):versions)
400                                 Nothing       -> addToFM mv_map mod [(name,version)]
401             where
402              (mod,_) = modAndOcc name
403              version = case lookupFM version_map name of
404                          Just v  -> v
405                          Nothing -> pprPanic "getVersionInfo:" (ppr PprDebug name)
406
407          import_versions = [ (mod, expectJust "import_versions" (lookupFM mod_versions_map mod), local_versions)
408                            | (mod, local_versions) <- fmToList mv_map
409                            ]
410
411          -- Question: should we filter the builtins out of import_versions?
412     in
413     returnRn import_versions
414 \end{code}
415
416 %*********************************************************
417 %*                                                      *
418 \subsection{Getting binders out of a declaration}
419 %*                                                      *
420 %*********************************************************
421
422 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
423 It's used for both source code (from @availsFromDecl@) and interface files
424 (from @loadDecl@).
425
426 It doesn't deal with source-code specific things: ValD, DefD.  They
427 are handled by the sourc-code specific stuff in RnNames.
428
429 \begin{code}
430 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)              -- New-name function
431                 -> RdrNameHsDecl
432                 -> RnMG AvailInfo
433
434 getDeclBinders new_name (TyD (TyData _ tycon _ condecls _ _ src_loc))
435   = new_name tycon src_loc                      `thenRn` \ tycon_name ->
436     getConFieldNames new_name condecls          `thenRn` \ sub_names ->
437     returnRn (Avail tycon_name sub_names)
438
439 getDeclBinders new_name (TyD (TyNew _ tycon _ (NewConDecl con _ con_loc) _ _ src_loc))
440   = new_name tycon src_loc              `thenRn` \ tycon_name ->
441     new_name con src_loc                `thenRn` \ con_name ->
442     returnRn (Avail tycon_name [con_name])
443
444 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
445   = new_name tycon src_loc              `thenRn` \ tycon_name ->
446     returnRn (Avail tycon_name [])
447
448 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
449   = new_name cname src_loc                      `thenRn` \ class_name ->
450     mapRn (getClassOpNames new_name) sigs       `thenRn` \ sub_names ->
451     returnRn (Avail class_name sub_names)
452
453 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
454   = new_name var src_loc                        `thenRn` \ var_name ->
455     returnRn (Avail var_name [])
456
457 getDeclBinders new_name (DefD _)  = returnRn NotAvailable
458 getDeclBinders new_name (InstD _) = returnRn NotAvailable
459
460 ----------------
461 getConFieldNames new_name (ConDecl con _ src_loc : rest)
462   = new_name con src_loc                `thenRn` \ n ->
463     getConFieldNames new_name rest      `thenRn` \ ns -> 
464     returnRn (n:ns)
465
466 getConFieldNames new_name (NewConDecl con _ src_loc : rest)
467   = new_name con src_loc                `thenRn` \ n ->
468     getConFieldNames new_name rest      `thenRn` \ ns -> 
469     returnRn (n:ns)
470
471 getConFieldNames new_name (ConOpDecl _ con _ src_loc : rest)
472   = new_name con src_loc                `thenRn` \ n ->
473     getConFieldNames new_name rest      `thenRn` \ ns -> 
474     returnRn (n:ns)
475
476 getConFieldNames new_name (RecConDecl con fielddecls src_loc : rest)
477   = mapRn (\n -> new_name n src_loc) (con:fields)       `thenRn` \ cfs ->
478     getConFieldNames new_name rest                      `thenRn` \ ns  -> 
479     returnRn (cfs ++ ns)
480   where
481     fields = concat (map fst fielddecls)
482
483 getConFieldNames new_name [] = returnRn []
484
485 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
486 \end{code}
487
488
489 %*********************************************************
490 %*                                                      *
491 \subsection{Reading an interface file}
492 %*                                                      *
493 %*********************************************************
494
495 \begin{code}
496 findAndReadIface :: Pretty -> Module -> RnMG (Maybe ParsedIface)
497         -- Nothing <=> file not found, or unreadable, or illegible
498         -- Just x  <=> successfully found and parsed 
499 findAndReadIface doc_str mod
500   = traceRn trace_msg                   `thenRn_`
501     getSearchPathRn                     `thenRn` \ dirs ->
502     try dirs dirs
503   where
504     trace_msg = ppHang (ppBesides [ppStr "Reading interface for ", 
505                                    pprModule PprDebug mod, ppSemi])
506                      4 (ppBesides [ppStr "reason: ", doc_str])
507
508     try all_dirs [] = traceRn (ppStr "...failed")       `thenRn_`
509                       returnRn Nothing
510
511     try all_dirs (dir:dirs)
512         = readIface file_path   `thenRn` \ read_result ->
513           case read_result of
514                 Nothing    -> try all_dirs dirs
515                 Just iface -> traceRn (ppStr "...done") `thenRn_`
516                               returnRn (Just iface)
517         where
518           file_path = dir ++ "/" ++ moduleString mod ++ ".hi"
519 \end{code}
520
521 @readIface@ trys just one file.
522
523 \begin{code}
524 readIface :: String -> RnMG (Maybe ParsedIface) 
525         -- Nothing <=> file not found, or unreadable, or illegible
526         -- Just x  <=> successfully found and parsed 
527 readIface file_path
528   = ioToRnMG (readFile file_path)       `thenRn` \ read_result ->
529     case read_result of
530         Right contents    -> case parseIface contents of
531                                 Failed err      -> failWithRn Nothing err 
532                                 Succeeded iface -> returnRn (Just iface)
533
534         Left  (NoSuchThing _) -> returnRn Nothing
535
536         Left  err             -> failWithRn Nothing
537                                             (cannaeReadFile file_path err)
538
539 \end{code}
540
541 mkSearchPath takes a string consisting of a colon-separated list of directories, and turns it into
542 a list of directories.  For example:
543
544         mkSearchPath "foo:.:baz"  =  ["foo", ".", "baz"]
545
546 \begin{code}
547 mkSearchPath :: Maybe String -> SearchPath
548 mkSearchPath Nothing = ["."]
549 mkSearchPath (Just s)
550   = go s
551   where
552     go "" = []
553     go s  = first : go (drop 1 rest)
554           where
555             (first,rest) = span (/= ':') s
556 \end{code}
557
558 %*********************************************************
559 %*                                                      *
560 \subsection{Errors}
561 %*                                                      *
562 %*********************************************************
563
564 \begin{code}
565 noIfaceErr mod sty
566   = ppBesides [ppStr "Could not find interface for ", ppQuote (pprModule sty mod)]
567 --      , ppStr " in"]) 4 (ppAboves (map ppStr dirs))
568
569 cannaeReadFile file err sty
570   = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]
571 \end{code}