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