b6f45211e9c943ab0a81588e95ef8654f1337380
[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_s ->
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 = (concat avails_s, 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, entities)
123   = mapRn load_entity entities
124   where
125     new_name occ = newGlobalName mod occ
126
127     load_entity (occ, occs)
128       = new_name occ            `thenRn` \ name ->
129         mapRn new_name occs     `thenRn` \ names ->
130         returnRn (Avail name names)
131
132 loadVersion :: Module -> VersionMap -> (OccName,Version) -> RnMG VersionMap
133 loadVersion mod vers_map (occ, version)
134   = newGlobalName mod occ                       `thenRn` \ name ->
135     returnRn (addToFM vers_map name version)
136
137
138 loadDecl :: Module -> (DeclsMap, VersionMap)
139          -> (Version, RdrNameHsDecl)
140          -> RnMG (DeclsMap, VersionMap)
141 loadDecl mod (decls_map, vers_map) (version, decl)
142   = getDeclBinders new_implicit_name decl       `thenRn` \ avail@(Avail name _) ->
143     returnRn (addListToFM decls_map
144                           [(name,(avail,decl)) | name <- availNames avail],
145               addToFM vers_map name version
146     )
147   where
148     new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
149
150 loadInstDecl :: Module -> Bag IfaceInst -> RdrNameInstDecl -> RnMG (Bag IfaceInst)
151 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
152   = initRnMS emptyRnEnv mod_name InterfaceMode $
153
154         -- Find out what type constructors and classes are mentioned in the
155         -- instance declaration.  We have to be a bit clever.
156         --
157         -- We want to rename the type so that we can find what
158         -- (free) type constructors are inside it.  But we must *not* thereby
159         -- put new occurrences into the global pool because otherwise we'll force
160         -- them all to be loaded.  We kill two birds with ones stone by renaming
161         -- with a fresh occurrence pool.
162     findOccurrencesRn (rnHsType inst_ty)        `thenRn` \ ty_names ->
163
164     returnRn ((ty_names, mod_name, decl) `consBag` insts)
165 \end{code}
166
167
168 %********************************************************
169 %*                                                      *
170 \subsection{Loading usage information}
171 %*                                                      *
172 %********************************************************
173
174 \begin{code}
175 checkUpToDate :: Module -> RnMG Bool            -- True <=> no need to recompile
176 checkUpToDate mod_name
177   = findAndReadIface doc_str mod_name           `thenRn` \ read_result ->
178     case read_result of
179         Nothing ->      -- Old interface file not found, so we'd better bale out
180                     traceRn (ppSep [ppStr "Didnt find old iface", pprModule PprDebug mod_name]) `thenRn_`
181                     returnRn False
182
183         Just (ParsedIface _ _ usages _ _ _ _ _) 
184                 ->      -- Found it, so now check it
185                     checkModUsage usages
186   where
187         -- Only look in current directory, with suffix .hi
188     doc_str = ppSep [ppStr "Need usage info from", pprModule PprDebug mod_name]
189
190
191 checkModUsage [] = returnRn True                -- Yes!  Everything is up to date!
192
193 checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
194   = loadInterface doc_str mod           `thenRn` \ ifaces ->
195     let
196         Ifaces _ mod_vers_map _ new_vers_map _ _ _ = ifaces
197         maybe_new_mod_vers = lookupFM mod_vers_map mod
198         Just new_mod_vers  = maybe_new_mod_vers
199     in
200         -- If we can't find a version number for the old module then
201         -- bale out saying things aren't up to date
202     if not (maybeToBool maybe_new_mod_vers) then
203         returnRn False
204     else
205
206         -- If the module version hasn't changed, just move on
207     if new_mod_vers == old_mod_vers then
208         traceRn (ppSep [ppStr "Module version unchanged:", pprModule PprDebug mod])     `thenRn_`
209         checkModUsage rest
210     else
211     traceRn (ppSep [ppStr "Module version has changed:", pprModule PprDebug mod])       `thenRn_`
212
213         -- New module version, so check entities inside
214     checkEntityUsage mod new_vers_map old_local_vers    `thenRn` \ up_to_date ->
215     if up_to_date then
216         traceRn (ppStr "...but the bits I use havn't.") `thenRn_`
217         checkModUsage rest      -- This one's ok, so check the rest
218     else
219         returnRn False          -- This one failed, so just bail out now
220   where
221     doc_str = ppSep [ppStr "need version info for", pprModule PprDebug mod]
222
223
224 checkEntityUsage mod new_vers_map [] 
225   = returnRn True       -- Yes!  All up to date!
226
227 checkEntityUsage mod new_vers_map ((occ_name,old_vers) : rest)
228   = newGlobalName mod occ_name          `thenRn` \ name ->
229     case lookupFM new_vers_map name of
230
231         Nothing       ->        -- We used it before, but it ain't there now
232                           traceRn (ppSep [ppStr "...and this no longer exported:", ppr PprDebug name])  `thenRn_`
233                           returnRn False
234
235         Just new_vers ->        -- It's there, but is it up to date?
236                           if new_vers == old_vers then
237                                 -- Up to date, so check the rest
238                                 checkEntityUsage mod new_vers_map rest
239                           else
240                                 traceRn (ppSep [ppStr "...and this is out of date:", ppr PprDebug name])  `thenRn_`
241                                 returnRn False  -- Out of date, so bale out
242 \end{code}
243
244
245 %*********************************************************
246 %*                                                      *
247 \subsection{Getting in a declaration}
248 %*                                                      *
249 %*********************************************************
250
251 \begin{code}
252 getDecl :: Name -> RnMG (AvailInfo, RdrNameHsDecl)
253 getDecl name
254   = traceRn doc_str                     `thenRn_`
255     loadInterface doc_str mod           `thenRn` \ (Ifaces _ _ _ _ decls_map _ _) ->
256     case lookupFM decls_map name of
257
258       Just avail_w_decl -> returnRn avail_w_decl
259
260       Nothing           ->      -- Can happen legitimately for "Optional" occurrences
261                            returnRn (NotAvailable, ValD EmptyBinds)
262   where
263      (mod,_) = modAndOcc name
264      doc_str = ppSep [ppStr "Need decl for", ppr PprDebug name]
265 \end{code}
266
267 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
268 It behaves exactly as if the wired in decl were actually in an interface file.
269 Specifically,
270   *     if the wired-in name is a data type constructor or a data constructor, 
271         it brings in the type constructor and all the data constructors; and
272         marks as "occurrences" any free vars of the data con.
273
274   *     similarly for synonum type constructor
275
276   *     if the wired-in name is another wired-in Id, it marks as "occurrences"
277         the free vars of the Id's type.
278
279   *     it loads the interface file for the wired-in thing for the
280         sole purpose of making sure that its instance declarations are available
281
282 All this is necessary so that we know all types that are "in play", so
283 that we know just what instances to bring into scope.
284         
285 \begin{code}
286 getWiredInDecl :: Name -> RnMG AvailInfo
287 getWiredInDecl name
288   =     -- Force in the home module in case it has instance decls for
289         -- the thing we are interested in
290     (if not is_tycon || mod == gHC__ then
291         returnRn ()                     -- Mini hack 1: no point for non-tycons; and if we
292                                         -- do this we find PrelNum trying to import PackedString,
293                                         -- because PrelBase's .hi file mentions PackedString.unpackString
294                                         -- But PackedString.hi isn't built by that point!
295                                         --
296                                         -- Mini hack 2; GHC is guaranteed not to have
297                                         -- instance decls, so it's a waste of time
298                                         -- to read it
299     else
300         loadInterface doc_str mod       `thenRn_`
301         returnRn ()
302     )                                           `thenRn_`
303
304     if is_tycon then
305         get_wired_tycon the_tycon
306     else                                -- Must be a wired-in-Id
307     if (isDataCon the_id) then          -- ... a wired-in data constructor
308         get_wired_tycon (dataConTyCon the_id)
309     else                                -- ... a wired-in non data-constructor
310         get_wired_id the_id
311   where
312     doc_str = ppSep [ppStr "Need home module for wired in thing", ppr PprDebug name]
313     (mod,_) = modAndOcc name
314     maybe_wired_in_tycon = maybeWiredInTyConName name
315     is_tycon             = maybeToBool maybe_wired_in_tycon
316     maybe_wired_in_id    = maybeWiredInIdName    name
317     Just the_tycon       = maybe_wired_in_tycon
318     Just the_id          = maybe_wired_in_id
319
320 get_wired_id id
321   = addImplicitOccsRn (nameSetToList id_mentioned)      `thenRn_`
322     returnRn (Avail (getName id) [])
323   where
324     id_mentioned         = namesOfType (idType id)
325
326 get_wired_tycon tycon 
327   | isSynTyCon tycon
328   = addImplicitOccsRn (nameSetToList mentioned)         `thenRn_`
329     returnRn (Avail (getName tycon) [])
330   where
331     (tyvars,ty) = getSynTyConDefn tycon
332     mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
333
334 get_wired_tycon tycon 
335   | otherwise           -- data or newtype
336   = addImplicitOccsRn (nameSetToList mentioned)         `thenRn_`
337     returnRn (Avail (getName tycon) (map getName data_cons))
338   where
339     data_cons = tyConDataCons tycon
340     mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
341 \end{code}
342
343
344 %*********************************************************
345 %*                                                      *
346 \subsection{Getting other stuff}
347 %*                                                      *
348 %*********************************************************
349
350 \begin{code}
351 getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
352 getInterfaceExports mod
353   = loadInterface doc_str mod           `thenRn` \ (Ifaces _ _ export_envs _ _ _ _) ->
354     case lookupFM export_envs mod of
355         Nothing ->      -- Not there; it must be that the interface file wasn't found;
356                         -- the error will have been reported already.
357                         -- (Actually loadInterface should put the empty export env in there
358                         --  anyway, but this does no harm.)
359                       returnRn ([],[])
360
361         Just stuff -> returnRn stuff
362   where
363     doc_str = ppSep [pprModule PprDebug mod, ppStr "is directly imported"]
364
365
366 getImportedInstDecls :: RnMG [IfaceInst]
367 getImportedInstDecls
368   =     -- First load any special-instance modules that aren't aready loaded
369     getSpecialInstModules                       `thenRn` \ inst_mods ->
370     mapRn load_it inst_mods                     `thenRn_`
371
372         -- Now we're ready to grab the instance declarations
373     getIfacesRn                                         `thenRn` \ ifaces ->
374     let
375          Ifaces _ _ _ _ _ insts _ = ifaces
376     in
377     returnRn (bagToList insts) 
378   where
379     load_it mod = loadInterface (doc_str mod) mod
380     doc_str mod = ppSep [pprModule PprDebug mod, ppStr "is a special-instance module"]
381
382 getSpecialInstModules :: RnMG [Module]
383 getSpecialInstModules 
384   = getIfacesRn                                         `thenRn` \ ifaces ->
385     let
386          Ifaces _ _ _ _ _ _ inst_mods = ifaces
387     in
388     returnRn inst_mods
389 \end{code}
390
391 \begin{code}
392 getImportVersions :: [AvailInfo]                        -- Imported avails
393                   -> RnMG (VersionInfo Name)    -- Version info for these names
394
395 getImportVersions imported_avails       
396   = getIfacesRn                                 `thenRn` \ ifaces ->
397     let
398          Ifaces _ mod_versions_map _ version_map _ _ _ = ifaces
399
400          -- import_versions is harder: we have to group together all the things imported
401          -- from a particular module.  We do this with yet another finite map
402
403          mv_map :: FiniteMap Module [LocalVersion Name]
404          mv_map            = foldl add_mv emptyFM imported_avails
405          add_mv mv_map (Avail name _) 
406             | isWiredInName name = mv_map       -- Don't record versions for wired-in names
407             | otherwise = case lookupFM mv_map mod of
408                                 Just versions -> addToFM mv_map mod ((name,version):versions)
409                                 Nothing       -> addToFM mv_map mod [(name,version)]
410             where
411              (mod,_) = modAndOcc name
412              version = case lookupFM version_map name of
413                          Just v  -> v
414                          Nothing -> pprPanic "getVersionInfo:" (ppr PprDebug name)
415
416          import_versions = [ (mod, expectJust "import_versions" (lookupFM mod_versions_map mod), local_versions)
417                            | (mod, local_versions) <- fmToList mv_map
418                            ]
419
420          -- Question: should we filter the builtins out of import_versions?
421     in
422     returnRn import_versions
423 \end{code}
424
425 %*********************************************************
426 %*                                                      *
427 \subsection{Getting binders out of a declaration}
428 %*                                                      *
429 %*********************************************************
430
431 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
432 It's used for both source code (from @availsFromDecl@) and interface files
433 (from @loadDecl@).
434
435 It doesn't deal with source-code specific things: ValD, DefD.  They
436 are handled by the sourc-code specific stuff in RnNames.
437
438 \begin{code}
439 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name)              -- New-name function
440                 -> RdrNameHsDecl
441                 -> RnMG AvailInfo
442
443 getDeclBinders new_name (TyD (TyData _ tycon _ condecls _ _ src_loc))
444   = new_name tycon src_loc                      `thenRn` \ tycon_name ->
445     getConFieldNames new_name condecls          `thenRn` \ sub_names ->
446     returnRn (Avail tycon_name sub_names)
447
448 getDeclBinders new_name (TyD (TyNew _ tycon _ (NewConDecl con _ con_loc) _ _ src_loc))
449   = new_name tycon src_loc              `thenRn` \ tycon_name ->
450     new_name con src_loc                `thenRn` \ con_name ->
451     returnRn (Avail tycon_name [con_name])
452
453 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
454   = new_name tycon src_loc              `thenRn` \ tycon_name ->
455     returnRn (Avail tycon_name [])
456
457 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
458   = new_name cname src_loc                      `thenRn` \ class_name ->
459     mapRn (getClassOpNames new_name) sigs       `thenRn` \ sub_names ->
460     returnRn (Avail class_name sub_names)
461
462 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
463   = new_name var src_loc                        `thenRn` \ var_name ->
464     returnRn (Avail var_name [])
465
466 getDeclBinders new_name (DefD _)  = returnRn NotAvailable
467 getDeclBinders new_name (InstD _) = returnRn NotAvailable
468
469 ----------------
470 getConFieldNames new_name (ConDecl con _ src_loc : rest)
471   = new_name con src_loc                `thenRn` \ n ->
472     getConFieldNames new_name rest      `thenRn` \ ns -> 
473     returnRn (n:ns)
474
475 getConFieldNames new_name (NewConDecl con _ src_loc : rest)
476   = new_name con src_loc                `thenRn` \ n ->
477     getConFieldNames new_name rest      `thenRn` \ ns -> 
478     returnRn (n:ns)
479
480 getConFieldNames new_name (ConOpDecl _ con _ src_loc : rest)
481   = new_name con src_loc                `thenRn` \ n ->
482     getConFieldNames new_name rest      `thenRn` \ ns -> 
483     returnRn (n:ns)
484
485 getConFieldNames new_name (RecConDecl con fielddecls src_loc : rest)
486   = mapRn (\n -> new_name n src_loc) (con:fields)       `thenRn` \ cfs ->
487     getConFieldNames new_name rest                      `thenRn` \ ns  -> 
488     returnRn (cfs ++ ns)
489   where
490     fields = concat (map fst fielddecls)
491
492 getConFieldNames new_name [] = returnRn []
493
494 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
495 \end{code}
496
497
498 %*********************************************************
499 %*                                                      *
500 \subsection{Reading an interface file}
501 %*                                                      *
502 %*********************************************************
503
504 \begin{code}
505 findAndReadIface :: Pretty -> Module -> RnMG (Maybe ParsedIface)
506         -- Nothing <=> file not found, or unreadable, or illegible
507         -- Just x  <=> successfully found and parsed 
508 findAndReadIface doc_str mod
509   = traceRn trace_msg                   `thenRn_`
510     getSearchPathRn                     `thenRn` \ dirs ->
511     try dirs dirs
512   where
513     trace_msg = ppHang (ppBesides [ppStr "Reading interface for ", 
514                                    pprModule PprDebug mod, ppSemi])
515                      4 (ppBesides [ppStr "reason: ", doc_str])
516
517     try all_dirs [] = traceRn (ppStr "...failed")       `thenRn_`
518                       returnRn Nothing
519
520     try all_dirs (dir:dirs)
521         = readIface file_path   `thenRn` \ read_result ->
522           case read_result of
523                 Nothing    -> try all_dirs dirs
524                 Just iface -> traceRn (ppStr "...done") `thenRn_`
525                               returnRn (Just iface)
526         where
527           file_path = dir ++ "/" ++ moduleString mod ++ ".hi"
528 \end{code}
529
530 @readIface@ trys just one file.
531
532 \begin{code}
533 readIface :: String -> RnMG (Maybe ParsedIface) 
534         -- Nothing <=> file not found, or unreadable, or illegible
535         -- Just x  <=> successfully found and parsed 
536 readIface file_path
537   = ioToRnMG (readFile file_path)       `thenRn` \ read_result ->
538     case read_result of
539         Right contents    -> case parseIface contents of
540                                 Failed err      -> failWithRn Nothing err 
541                                 Succeeded iface -> returnRn (Just iface)
542
543         Left  (NoSuchThing _) -> returnRn Nothing
544
545         Left  err             -> failWithRn Nothing
546                                             (cannaeReadFile file_path err)
547
548 \end{code}
549
550 mkSearchPath takes a string consisting of a colon-separated list of directories, and turns it into
551 a list of directories.  For example:
552
553         mkSearchPath "foo:.:baz"  =  ["foo", ".", "baz"]
554
555 \begin{code}
556 mkSearchPath :: Maybe String -> SearchPath
557 mkSearchPath Nothing = ["."]
558 mkSearchPath (Just s)
559   = go s
560   where
561     go "" = []
562     go s  = first : go (drop 1 rest)
563           where
564             (first,rest) = span (/= ':') s
565 \end{code}
566
567 %*********************************************************
568 %*                                                      *
569 \subsection{Errors}
570 %*                                                      *
571 %*********************************************************
572
573 \begin{code}
574 noIfaceErr mod sty
575   = ppBesides [ppStr "Could not find interface for ", ppQuote (pprModule sty mod)]
576 --      , ppStr " in"]) 4 (ppAboves (map ppStr dirs))
577
578 cannaeReadFile file err sty
579   = ppBesides [ppPStr SLIT("Failed in reading file: "), ppStr file, ppStr "; error=", ppStr (show err)]
580 \end{code}