[project @ 2000-10-24 15:55:35 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnHiFiles.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Dealing with interface files}
5
6 \begin{code}
7 module RnHiFiles (
8         findAndReadIface, loadInterface, loadHomeInterface, 
9         tryLoadInterface, loadOrphanModules,
10         loadExports, loadFixDecls, loadDeprecs,
11
12         getTyClDeclBinders, 
13         removeContext           -- removeContext probably belongs somewhere else
14    ) where
15
16 #include "HsVersions.h"
17
18 import CmdLineOpts      ( opt_IgnoreIfacePragmas )
19 import HscTypes
20 import HsSyn            ( HsDecl(..), TyClDecl(..), InstDecl(..),
21                           HsType(..), ConDecl(..), 
22                           FixitySig(..), RuleDecl(..),
23                           tyClDeclNames
24                         )
25 import RdrHsSyn         ( RdrNameTyClDecl, RdrNameInstDecl, RdrNameRuleDecl,
26                           extractHsTyRdrNames 
27                         )
28 import BasicTypes       ( Version )
29 import RnEnv
30 import RnMonad
31 import ParseIface       ( parseIface, IfaceStuff(..) )
32
33 import Name             ( Name {-instance NamedThing-}, nameOccName,
34                           nameModule,
35                           NamedThing(..),
36                           mkNameEnv, extendNameEnv
37                          )
38 import Module           ( Module,
39                           moduleName, isModuleInThisPackage,
40                           ModuleName, WhereFrom(..),
41                           extendModuleEnv, lookupModuleEnvByName,
42                         )
43 import RdrName          ( RdrName, rdrNameOcc )
44 import NameSet
45 import SrcLoc           ( mkSrcLoc, SrcLoc )
46 import Maybes           ( maybeToBool )
47 import StringBuffer     ( hGetStringBuffer )
48 import FastString       ( mkFastString )
49 import ErrUtils         ( Message )
50 import Lex
51 import FiniteMap
52 import Outputable
53 import Bag
54 \end{code}
55
56
57 %*********************************************************
58 %*                                                      *
59 \subsection{Loading a new interface file}
60 %*                                                      *
61 %*********************************************************
62
63 \begin{code}
64 loadHomeInterface :: SDoc -> Name -> RnM d Ifaces
65 loadHomeInterface doc_str name
66   = loadInterface doc_str (moduleName (nameModule name)) ImportBySystem
67
68 loadOrphanModules :: [ModuleName] -> RnM d ()
69 loadOrphanModules mods
70   | null mods = returnRn ()
71   | otherwise = traceRn (text "Loading orphan modules:" <+> 
72                          fsep (map ppr mods))                   `thenRn_` 
73                 mapRn_ load mods                                `thenRn_`
74                 returnRn ()
75   where
76     load mod   = loadInterface (mk_doc mod) mod ImportBySystem
77     mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
78
79 loadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d Ifaces
80 loadInterface doc mod from 
81   = tryLoadInterface doc mod from       `thenRn` \ (ifaces, maybe_err) ->
82     case maybe_err of
83         Nothing  -> returnRn ifaces
84         Just err -> failWithRn ifaces err
85
86 tryLoadInterface :: SDoc -> ModuleName -> WhereFrom -> RnM d (Ifaces, Maybe Message)
87         -- Returns (Just err) if an error happened
88         -- Guarantees to return with iImpModInfo m --> (..., True)
89         -- (If the load fails, we plug in a vanilla placeholder)
90 tryLoadInterface doc_str mod_name from
91  = getHomeIfaceTableRn          `thenRn` \ hit ->
92    getIfacesRn                  `thenRn` \ ifaces ->
93         
94         -- Check whether we have it already in the home package
95    case lookupModuleEnvByName hit mod_name of {
96         Just _  -> returnRn (ifaces, Nothing) ; -- In the home package
97         Nothing -> 
98
99    let
100         mod_map  = iImpModInfo ifaces
101         mod_info = lookupFM mod_map mod_name
102
103         hi_boot_file 
104           = case (from, mod_info) of
105                 (ImportByUser,       _)                -> False         -- Not hi-boot
106                 (ImportByUserSource, _)                -> True          -- hi-boot
107                 (ImportBySystem, Just (_, is_boot, _)) -> is_boot       -- 
108                 (ImportBySystem, Nothing)              -> False
109                         -- We're importing a module we know absolutely
110                         -- nothing about, so we assume it's from
111                         -- another package, where we aren't doing 
112                         -- dependency tracking. So it won't be a hi-boot file.
113
114         redundant_source_import 
115           = case (from, mod_info) of 
116                 (ImportByUserSource, Just (_,False,_)) -> True
117                 other                                  -> False
118    in
119         -- CHECK WHETHER WE HAVE IT ALREADY
120    case mod_info of {
121         Just (_, _, True)
122                 ->      -- We're read it already so don't re-read it
123                     returnRn (ifaces, Nothing) ;
124
125         _ ->
126
127         -- Issue a warning for a redundant {- SOURCE -} import
128         -- NB that we arrange to read all the ordinary imports before 
129         -- any of the {- SOURCE -} imports
130    warnCheckRn  (not redundant_source_import)
131                 (warnRedundantSourceImport mod_name)    `thenRn_`
132
133         -- READ THE MODULE IN
134    findAndReadIface doc_str mod_name hi_boot_file   `thenRn` \ read_result ->
135    case read_result of {
136         Left err ->     -- Not found, so add an empty export env to the Ifaces map
137                         -- so that we don't look again
138            let
139                 new_mod_map = addToFM mod_map mod_name (False, False, True)
140                 new_ifaces  = ifaces { iImpModInfo = new_mod_map }
141            in
142            setIfacesRn new_ifaces               `thenRn_`
143            returnRn (new_ifaces, Just err) ;
144
145         -- Found and parsed!
146         Right (mod, iface) ->
147
148         -- LOAD IT INTO Ifaces
149
150         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
151         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
152         --     If we do loadExport first the wrong info gets into the cache (unless we
153         --      explicitly tag each export which seems a bit of a bore)
154
155
156         -- Sanity check.  If we're system-importing a module we know nothing at all
157         -- about, it should be from a different package to this one
158     WARN( not (maybeToBool mod_info) && 
159           case from of { ImportBySystem -> True; other -> False } &&
160           isModuleInThisPackage mod,
161           ppr mod )
162
163     loadDecls mod               (iDecls ifaces)   (pi_decls iface)      `thenRn` \ (decls_vers, new_decls) ->
164     loadRules mod               (iRules ifaces)   (pi_rules iface)      `thenRn` \ (rule_vers, new_rules) ->
165     foldlRn (loadInstDecl mod)  (iInsts ifaces)   (pi_insts iface)      `thenRn` \ new_insts ->
166     loadExports                                   (pi_exports iface)    `thenRn` \ (export_vers, avails) ->
167     loadFixDecls mod                              (pi_fixity iface)     `thenRn` \ fix_env ->
168     loadDeprecs mod                               (pi_deprecs iface)    `thenRn` \ deprec_env ->
169     let
170         version = VersionInfo { vers_module  = pi_vers iface, 
171                                 vers_exports = export_vers,
172                                 vers_rules = rule_vers,
173                                 vers_decls = decls_vers }
174
175         -- For an explicit user import, add to mod_map info about
176         -- the things the imported module depends on, extracted
177         -- from its usage info.
178         mod_map1 = case from of
179                         ImportByUser -> addModDeps mod (pi_usages iface) mod_map
180                         other        -> mod_map
181         mod_map2 = addToFM mod_map1 mod_name (has_orphans, hi_boot_file, True)
182
183         -- Now add info about this module to the PIT
184         has_orphans = pi_orphan iface
185         new_pit   = extendModuleEnv (iPIT ifaces) mod mod_iface
186         mod_iface = ModIface { mi_module = mod, mi_version = version,
187                                mi_exports = avails, mi_orphan = has_orphans,
188                                mi_fixities = fix_env, mi_deprecs = deprec_env,
189                                mi_usages  = [], -- Will be filled in later
190                                mi_decls   = panic "No mi_decls in PIT",
191                                mi_globals = panic "No mi_globals in PIT"
192                     }
193
194         new_ifaces = ifaces { iPIT        = new_pit,
195                               iDecls      = new_decls,
196                               iInsts      = new_insts,
197                               iRules      = new_rules,
198                               iImpModInfo = mod_map2  }
199     in
200     setIfacesRn new_ifaces              `thenRn_`
201     returnRn (new_ifaces, Nothing)
202     }}}
203
204 -----------------------------------------------------
205 --      Adding module dependencies from the 
206 --      import decls in the interface file
207 -----------------------------------------------------
208
209 addModDeps :: Module -> [ImportVersion a] 
210            -> ImportedModuleInfo -> ImportedModuleInfo
211 -- (addModDeps M ivs deps)
212 -- We are importing module M, and M.hi contains 'import' decls given by ivs
213 addModDeps mod new_deps mod_deps
214   = foldr add mod_deps filtered_new_deps
215   where
216         -- Don't record dependencies when importing a module from another package
217         -- Except for its descendents which contain orphans,
218         -- and in that case, forget about the boot indicator
219     filtered_new_deps :: [(ModuleName, (WhetherHasOrphans, IsBootInterface, IsLoaded))]
220     filtered_new_deps
221         | isModuleInThisPackage mod 
222                             = [ (imp_mod, (has_orphans, is_boot, False))
223                               | (imp_mod, has_orphans, is_boot, _) <- new_deps 
224                               ]                       
225         | otherwise         = [ (imp_mod, (True, False, False))
226                               | (imp_mod, has_orphans, _, _) <- new_deps, 
227                                 has_orphans
228                               ]
229     add (imp_mod, dep) deps = addToFM_C combine deps imp_mod dep
230
231     combine old@(_, old_is_boot, old_is_loaded) new
232         | old_is_loaded || not old_is_boot = old        -- Keep the old info if it's already loaded
233                                                         -- or if it's a non-boot pending load
234         | otherwise                         = new       -- Otherwise pick new info
235
236
237 -----------------------------------------------------
238 --      Loading the export list
239 -----------------------------------------------------
240
241 loadExports :: (Version, [ExportItem]) -> RnM d (Version, Avails)
242 loadExports (vers, items)
243   = getModuleRn                                 `thenRn` \ this_mod ->
244     mapRn (loadExport this_mod) items           `thenRn` \ avails_s ->
245     returnRn (vers, concat avails_s)
246
247
248 loadExport :: Module -> ExportItem -> RnM d [AvailInfo]
249 loadExport this_mod (mod, entities)
250   | mod == moduleName this_mod = returnRn []
251         -- If the module exports anything defined in this module, just ignore it.
252         -- Reason: otherwise it looks as if there are two local definition sites
253         -- for the thing, and an error gets reported.  Easiest thing is just to
254         -- filter them out up front. This situation only arises if a module
255         -- imports itself, or another module that imported it.  (Necessarily,
256         -- this invoves a loop.)  Consequence: if you say
257         --      module A where
258         --         import B( AType )
259         --         type AType = ...
260         --
261         --      module B( AType ) where
262         --         import {-# SOURCE #-} A( AType )
263         --
264         -- then you'll get a 'B does not export AType' message.  A bit bogus
265         -- but it's a bogus thing to do!
266
267   | otherwise
268   = mapRn (load_entity mod) entities
269   where
270     new_name mod occ = newGlobalName mod occ
271
272     load_entity mod (Avail occ)
273       = new_name mod occ        `thenRn` \ name ->
274         returnRn (Avail name)
275     load_entity mod (AvailTC occ occs)
276       = new_name mod occ              `thenRn` \ name ->
277         mapRn (new_name mod) occs     `thenRn` \ names ->
278         returnRn (AvailTC name names)
279
280
281 -----------------------------------------------------
282 --      Loading type/class/value decls
283 -----------------------------------------------------
284
285 loadDecls :: Module 
286           -> DeclsMap
287           -> [(Version, RdrNameTyClDecl)]
288           -> RnM d (NameEnv Version, DeclsMap)
289 loadDecls mod decls_map decls
290   = foldlRn (loadDecl mod) (emptyNameEnv, decls_map) decls
291
292 loadDecl :: Module 
293          -> (NameEnv Version, DeclsMap)
294          -> (Version, RdrNameTyClDecl)
295          -> RnM d (NameEnv Version, DeclsMap)
296 loadDecl mod (version_map, decls_map) (version, decl)
297   = getIfaceDeclBinders new_name decl   `thenRn` \ full_avail ->
298     let
299         main_name     = availName full_avail
300         new_decls_map = extendNameEnvList decls_map stuff
301         stuff         = [ (name, (full_avail, name==main_name, (mod, decl))) 
302                         | name <- availNames full_avail]
303
304         new_version_map = extendNameEnv version_map main_name version
305     in
306     returnRn (new_version_map, new_decls_map)
307   where
308         -- newTopBinder puts into the cache the binder with the
309         -- module information set correctly.  When the decl is later renamed,
310         -- the binding site will thereby get the correct module.
311         -- There maybe occurrences that don't have the correct Module, but
312         -- by the typechecker will propagate the binding definition to all 
313         -- the occurrences, so that doesn't matter
314     new_name rdr_name loc = newTopBinder mod rdr_name loc
315
316
317 -----------------------------------------------------
318 --      Loading fixity decls
319 -----------------------------------------------------
320
321 loadFixDecls mod decls
322   = mapRn (loadFixDecl mod_name) decls  `thenRn` \ to_add ->
323     returnRn (mkNameEnv to_add)
324   where
325     mod_name = moduleName mod
326
327 loadFixDecl mod_name sig@(FixitySig rdr_name fixity loc)
328   = newGlobalName mod_name (rdrNameOcc rdr_name)        `thenRn` \ name ->
329     returnRn (name, fixity)
330
331
332 -----------------------------------------------------
333 --      Loading instance decls
334 -----------------------------------------------------
335
336 loadInstDecl :: Module
337              -> IfaceInsts
338              -> RdrNameInstDecl
339              -> RnM d IfaceInsts
340 loadInstDecl mod insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
341   = 
342         -- Find out what type constructors and classes are "gates" for the
343         -- instance declaration.  If all these "gates" are slurped in then
344         -- we should slurp the instance decl too.
345         -- 
346         -- We *don't* want to count names in the context part as gates, though.
347         -- For example:
348         --              instance Foo a => Baz (T a) where ...
349         --
350         -- Here the gates are Baz and T, but *not* Foo.
351     let 
352         munged_inst_ty = removeContext inst_ty
353         free_names     = extractHsTyRdrNames munged_inst_ty
354     in
355     setModuleRn mod $
356     mapRn lookupOrigName free_names     `thenRn` \ gate_names ->
357     returnRn ((mkNameSet gate_names, (mod, InstD decl)) `consBag` insts)
358
359
360 -- In interface files, the instance decls now look like
361 --      forall a. Foo a -> Baz (T a)
362 -- so we have to strip off function argument types as well
363 -- as the bit before the '=>' (which is always empty in interface files)
364 removeContext (HsForAllTy tvs cxt ty) = HsForAllTy tvs [] (removeFuns ty)
365 removeContext ty                      = removeFuns ty
366
367 removeFuns (HsFunTy _ ty) = removeFuns ty
368 removeFuns ty               = ty
369
370
371 -----------------------------------------------------
372 --      Loading Rules
373 -----------------------------------------------------
374
375 loadRules :: Module -> IfaceRules 
376           -> (Version, [RdrNameRuleDecl])
377           -> RnM d (Version, IfaceRules)
378 loadRules mod rule_bag (version, rules)
379   | null rules || opt_IgnoreIfacePragmas 
380   = returnRn (version, rule_bag)
381   | otherwise
382   = setModuleRn mod                     $
383     mapRn (loadRule mod) rules          `thenRn` \ new_rules ->
384     returnRn (version, rule_bag `unionBags` listToBag new_rules)
385
386 loadRule :: Module -> RdrNameRuleDecl -> RnM d GatedDecl
387 -- "Gate" the rule simply by whether the rule variable is
388 -- needed.  We can refine this later.
389 loadRule mod decl@(IfaceRule _ _ var _ _ src_loc)
390   = lookupOrigName var          `thenRn` \ var_name ->
391     returnRn (unitNameSet var_name, (mod, RuleD decl))
392
393
394 -----------------------------------------------------
395 --      Loading Deprecations
396 -----------------------------------------------------
397
398 loadDeprecs :: Module -> IfaceDeprecs -> RnM d Deprecations
399 loadDeprecs m Nothing                                  = returnRn NoDeprecs
400 loadDeprecs m (Just (Left txt))  = returnRn (DeprecAll txt)
401 loadDeprecs m (Just (Right prs)) = setModuleRn m                                $
402                                    foldlRn loadDeprec emptyNameEnv prs  `thenRn` \ env ->
403                                    returnRn (DeprecSome env)
404 loadDeprec deprec_env (n, txt)
405   = lookupOrigName n            `thenRn` \ name ->
406     traceRn (text "Loaded deprecation(s) for" <+> ppr name <> colon <+> ppr txt) `thenRn_`
407     returnRn (extendNameEnv deprec_env name txt)
408 \end{code}
409
410
411 %*********************************************************
412 %*                                                      *
413 \subsection{Getting binders out of a declaration}
414 %*                                                      *
415 %*********************************************************
416
417 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
418 It's used for both source code (from @availsFromDecl@) and interface files
419 (from @loadDecl@).
420
421 It doesn't deal with source-code specific things: @ValD@, @DefD@.  They
422 are handled by the sourc-code specific stuff in @RnNames@.
423
424 \begin{code}
425 getIfaceDeclBinders, getTyClDeclBinders
426         :: (RdrName -> SrcLoc -> RnM d Name)    -- New-name function
427         -> RdrNameTyClDecl
428         -> RnM d AvailInfo
429
430 getIfaceDeclBinders new_name tycl_decl
431   = getTyClDeclBinders    new_name tycl_decl    `thenRn` \ avail ->
432     getSysTyClDeclBinders new_name tycl_decl    `thenRn` \ extras ->
433     returnRn (addSysAvails avail extras)
434                 -- Add the sys-binders to avail.  When we import the decl,
435                 -- it's full_avail that will get added to the 'already-slurped' set (iSlurp)
436                 -- If we miss out sys-binders, we'll read the decl multiple times!
437
438 getTyClDeclBinders new_name (IfaceSig var ty prags src_loc)
439   = new_name var src_loc                        `thenRn` \ var_name ->
440     returnRn (Avail var_name)
441
442 getTyClDeclBinders new_name tycl_decl
443   = mapRn do_one (tyClDeclNames tycl_decl)      `thenRn` \ (main_name:sub_names) ->
444     returnRn (AvailTC main_name (main_name : sub_names))
445   where
446     do_one (name,loc) = new_name name loc
447 \end{code}
448
449 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
450 A the moment that's just the tycon and datacon that come with a class decl.
451 They aren't returned by @getDeclBinders@ because they aren't in scope;
452 but they {\em should} be put into the @DeclsMap@ of this module.
453
454 Note that this excludes the default-method names of a class decl,
455 and the dict fun of an instance decl, because both of these have 
456 bindings of their own elsewhere.
457
458 \begin{code}
459 getSysTyClDeclBinders new_name (ClassDecl _ cname _ _ sigs _ names src_loc)
460   = sequenceRn [new_name n src_loc | n <- names]
461
462 getSysTyClDeclBinders new_name (TyData _ _ _ _ cons _ _ _ _ _)
463   = sequenceRn [new_name wkr_name src_loc | ConDecl _ wkr_name _ _ _ src_loc <- cons]
464
465 getSysTyClDeclBinders new_name other_decl
466   = returnRn []
467 \end{code}
468
469
470
471 %*********************************************************
472 %*                                                      *
473 \subsection{Reading an interface file}
474 %*                                                      *
475 %*********************************************************
476
477 \begin{code}
478 findAndReadIface :: SDoc -> ModuleName 
479                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
480                                         -- False <=> Look for .hi file
481                  -> RnM d (Either Message (Module, ParsedIface))
482         -- Nothing <=> file not found, or unreadable, or illegible
483         -- Just x  <=> successfully found and parsed 
484
485 findAndReadIface doc_str mod_name hi_boot_file
486   = traceRn trace_msg                   `thenRn_`
487
488     getFinderRn                         `thenRn` \ finder ->
489     ioToRnM (finder mod_name)           `thenRn` \ maybe_found ->
490
491     case maybe_found of
492       Right (Just (mod,locn))
493         | hi_boot_file -> readIface mod (hi_file locn ++ "-hi-boot")
494         | otherwise    -> readIface mod (hi_file locn)
495         
496         -- Can't find it
497       other   -> traceRn (ptext SLIT("...not found"))   `thenRn_`
498                  returnRn (Left (noIfaceErr mod_name hi_boot_file))
499
500   where
501     trace_msg = sep [hsep [ptext SLIT("Reading"), 
502                            if hi_boot_file then ptext SLIT("[boot]") else empty,
503                            ptext SLIT("interface for"), 
504                            ppr mod_name <> semi],
505                      nest 4 (ptext SLIT("reason:") <+> doc_str)]
506 \end{code}
507
508 @readIface@ tries just the one file.
509
510 \begin{code}
511 readIface :: Module -> String -> RnM d (Either Message (Module, ParsedIface))
512         -- Nothing <=> file not found, or unreadable, or illegible
513         -- Just x  <=> successfully found and parsed 
514 readIface wanted_mod file_path
515   = traceRn (ptext SLIT("...reading from") <+> text file_path)  `thenRn_`
516     ioToRnM (hGetStringBuffer False file_path)                   `thenRn` \ read_result ->
517     case read_result of
518         Right contents    -> 
519              case parseIface contents
520                         PState{ bol = 0#, atbol = 1#,
521                                 context = [],
522                                 glasgow_exts = 1#,
523                                 loc = mkSrcLoc (mkFastString file_path) 1 } of
524                   POk _  (PIface iface) ->
525                       warnCheckRn (wanted_mod == read_mod)
526                                   (hiModuleNameMismatchWarn wanted_mod read_mod) `thenRn_`
527                       returnRn (Right (wanted_mod, iface))
528                     where
529                       read_mod = pi_mod iface
530
531                   PFailed err   -> bale_out err
532                   parse_result  -> bale_out empty
533                         -- This last case can happen if the interface file is (say) empty
534                         -- in which case the parser thinks it looks like an IdInfo or
535                         -- something like that.  Just an artefact of the fact that the
536                         -- parser is used for several purposes at once.
537
538         Left io_err -> bale_out (text (show io_err))
539   where
540     bale_out err = returnRn (Left (badIfaceFile file_path err))
541 \end{code}
542
543
544 %*********************************************************
545 %*                                                       *
546 \subsection{Errors}
547 %*                                                       *
548 %*********************************************************
549
550 \begin{code}
551 noIfaceErr mod_name boot_file
552   = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
553         -- We used to print the search path, but we can't do that
554         -- now, because it's hidden inside the finder.
555         -- Maybe the finder should expose more functions.
556
557 badIfaceFile file err
558   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
559           nest 4 err]
560
561 hiModuleNameMismatchWarn :: Module -> Module  -> Message
562 hiModuleNameMismatchWarn requested_mod read_mod = 
563     hsep [ ptext SLIT("Something is amiss; requested module name")
564          , ppr (moduleName requested_mod)
565          , ptext SLIT("differs from name found in the interface file")
566          , ppr read_mod
567          ]
568
569 warnRedundantSourceImport mod_name
570   = ptext SLIT("Unnecessary {- SOURCE -} in the import of module")
571           <+> quotes (ppr mod_name)
572 \end{code}
573