[project @ 1998-04-06 18:38:36 by sof]
[ghc-hetmet.git] / ghc / compiler / rename / Rename.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-1996
3 %
4 \section[Rename]{Renaming and dependency analysis passes}
5
6 \begin{code}
7 module Rename ( renameModule ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn
12 import RdrHsSyn         ( RdrName(..), RdrNameHsModule )
13 import RnHsSyn          ( RenamedHsModule, RenamedHsDecl, extractHsTyNames )
14
15 import CmdLineOpts      ( opt_HiMap, opt_D_show_rn_trace,
16                           opt_D_dump_rn, opt_D_show_rn_stats,
17                           opt_WarnUnusedBinds, opt_WarnUnusedImports
18                         )
19 import RnMonad
20 import RnNames          ( getGlobalNames )
21 import RnSource         ( rnDecl )
22 import RnIfaces         ( getImportedInstDecls, importDecl, getImportVersions, getSpecialInstModules,
23                           getDeferredDataDecls,
24                           mkSearchPath, getSlurpedNames, getRnStats
25                         )
26 import RnEnv            ( addImplicitOccsRn, availNames )
27 import Name             ( Name, PrintUnqualified, Provenance, isLocallyDefined,
28                           NameSet(..),
29                           nameSetToList, minusNameSet, NamedThing(..),
30                           nameModule, pprModule, pprOccName, nameOccName
31                         )
32 import TysWiredIn       ( unitTyCon, intTyCon, doubleTyCon )
33 import TyCon            ( TyCon )
34 import PrelMods         ( mAIN, pREL_MAIN )
35 import PrelInfo         ( ioTyCon_NAME )
36 import ErrUtils         ( pprBagOfErrors, pprBagOfWarnings,
37                           doIfSet, dumpIfSet, ghcExit
38                         )
39 import Bag              ( isEmptyBag )
40 import FiniteMap        ( fmToList, delListFromFM )
41 import UniqSupply       ( UniqSupply )
42 import Util             ( equivClasses )
43 import Maybes           ( maybeToBool )
44 import List             ( partition )
45 import Outputable
46 \end{code}
47
48
49
50 \begin{code}
51 renameModule :: UniqSupply
52              -> RdrNameHsModule
53              -> IO (Maybe 
54                       ( RenamedHsModule   -- Output, after renaming
55                       , InterfaceDetails  -- Interface; for interface file generatino
56                       , RnNameSupply      -- Final env; for renaming derivings
57                       , [Module]          -- Imported modules; for profiling
58                       ))
59
60 renameModule us this_mod@(HsModule mod_name vers exports imports fixities local_decls loc)
61   =     -- Initialise the renamer monad
62     initRn mod_name us (mkSearchPath opt_HiMap) loc
63            (rename this_mod)                            >>=
64         \ (maybe_rn_stuff, rn_errs_bag, rn_warns_bag) ->
65
66         -- Check for warnings
67     doIfSet (not (isEmptyBag rn_warns_bag))
68             (printErrs (pprBagOfWarnings rn_warns_bag)) >>
69
70         -- Check for errors; exit if so
71     doIfSet (not (isEmptyBag rn_errs_bag))
72             (printErrs (pprBagOfErrors rn_errs_bag)      >>
73              ghcExit 1
74             )                                            >>
75
76         -- Dump output, if any
77     (case maybe_rn_stuff of
78         Nothing  -> return ()
79         Just results@(rn_mod, _, _, _)
80                  -> dumpIfSet opt_D_dump_rn "Renamer:"
81                               (ppr rn_mod)
82     )                                                   >>
83
84         -- Return results
85     return maybe_rn_stuff
86 \end{code}
87
88
89 \begin{code}
90 rename this_mod@(HsModule mod_name vers exports imports fixities local_decls loc)
91   =     -- FIND THE GLOBAL NAME ENVIRONMENT
92     getGlobalNames this_mod                     `thenRn` \ maybe_stuff ->
93
94         -- CHECK FOR EARLY EXIT
95     if not (maybeToBool maybe_stuff) then
96         -- Everything is up to date; no need to recompile further
97         rnStats []              `thenRn_`
98         returnRn Nothing
99     else
100     let
101         Just (export_env, rn_env, explicit_info, print_unqual) = maybe_stuff
102     in
103
104         -- RENAME THE SOURCE
105     initRnMS rn_env mod_name SourceMode (
106         addImplicits mod_name                           `thenRn_`
107         mapRn rnDecl local_decls
108     )                                                   `thenRn` \ rn_local_decls ->
109
110         -- SLURP IN ALL THE NEEDED DECLARATIONS
111     slurpDecls print_unqual rn_local_decls              `thenRn` \ rn_all_decls ->
112
113         -- EXIT IF ERRORS FOUND
114     checkErrsRn                         `thenRn` \ no_errs_so_far ->
115     if not no_errs_so_far then
116         -- Found errors already, so exit now
117         rnStats []              `thenRn_`
118         returnRn Nothing
119     else
120
121         -- GENERATE THE VERSION/USAGE INFO
122     getImportVersions mod_name exports                  `thenRn` \ import_versions ->
123     getNameSupplyRn                                     `thenRn` \ name_supply ->
124
125         -- REPORT UNUSED NAMES
126     reportUnusedNames export_env explicit_info          `thenRn_`
127
128         -- GENERATE THE SPECIAL-INSTANCE MODULE LIST
129         -- The "special instance" modules are those modules that contain instance
130         -- declarations that contain no type constructor or class that was declared
131         -- in that module.
132     getSpecialInstModules                               `thenRn` \ imported_special_inst_mods ->
133     let
134         special_inst_decls = [d | InstD d@(InstDecl inst_ty _ _ _ _) <- rn_local_decls,
135                                   all (not.isLocallyDefined) (nameSetToList (extractHsTyNames inst_ty))
136                              ]
137         special_inst_mods | null special_inst_decls = imported_special_inst_mods
138                           | otherwise               = mod_name : imported_special_inst_mods
139     in
140                   
141     
142         -- RETURN THE RENAMED MODULE
143     let
144         import_mods = [mod | ImportDecl mod _ _ _ _ _ <- imports]
145
146         renamed_module = HsModule mod_name vers 
147                                   trashed_exports trashed_imports trashed_fixities
148                                   rn_all_decls
149                                   loc
150     in
151     rnStats rn_all_decls        `thenRn_`
152     returnRn (Just (renamed_module, 
153                     (import_versions, export_env, special_inst_mods),
154                      name_supply,
155                      import_mods))
156   where
157     trashed_exports  = {-trace "rnSource:trashed_exports"-} Nothing
158     trashed_imports  = {-trace "rnSource:trashed_imports"-} []
159     trashed_fixities = []
160 \end{code}
161
162 @addImplicits@ forces the renamer to slurp in some things which aren't
163 mentioned explicitly, but which might be needed by the type checker.
164
165 \begin{code}
166 addImplicits mod_name
167   = addImplicitOccsRn (implicit_main ++ default_tys)
168   where
169         -- Add occurrences for Int, Double, and (), because they
170         -- are the types to which ambigious type variables may be defaulted by
171         -- the type checker; so they won't every appear explicitly.
172         -- [The () one is a GHC extension for defaulting CCall results.]
173     default_tys = [getName intTyCon, getName doubleTyCon, getName unitTyCon ]
174
175         -- Add occurrences for IO or PrimIO
176     implicit_main |  mod_name == mAIN
177                   || mod_name == pREL_MAIN = [ioTyCon_NAME]
178                   |  otherwise            = []
179 \end{code}
180
181
182 \begin{code}
183 slurpDecls print_unqual decls
184   =     -- First of all, get all the compulsory decls
185     slurp_compulsories decls    `thenRn` \ decls1 ->
186
187         -- Next get the optional ones
188     closeDecls optional_mode decls1     `thenRn` \ decls2 ->
189
190         -- Finally get those deferred data type declarations
191     getDeferredDataDecls                                `thenRn` \ data_decls ->
192     mapRn (rn_data_decl compulsory_mode) data_decls     `thenRn` \ rn_data_decls ->
193
194         -- Done
195     returnRn (rn_data_decls ++ decls2)
196
197   where
198     compulsory_mode = InterfaceMode Compulsory print_unqual
199     optional_mode   = InterfaceMode Optional   print_unqual
200
201         -- The "slurp_compulsories" function is a loop that alternates
202         -- between slurping compulsory decls and slurping the instance
203         -- decls thus made relavant.
204         -- We *must* loop again here.  Why?  Two reasons:
205         -- (a) an instance decl will give rise to an unresolved dfun, whose
206         --      decl we must slurp to get its version number; that's the version
207         --      number for the whole instance decl.  (And its unfolding might mention new
208         --  unresolved names.)
209         -- (b) an instance decl might give rise to a new unresolved class,
210         --      whose decl we must slurp, which might let in some new instance decls,
211         --      and so on.  Example:  instance Foo a => Baz [a] where ...
212     slurp_compulsories decls
213       = closeDecls compulsory_mode decls        `thenRn` \ decls1 ->
214         
215                 -- Instance decls still pending?
216         getImportedInstDecls                    `thenRn` \ inst_decls ->
217         if null inst_decls then 
218                 -- No, none
219             returnRn decls1
220         else
221                 -- Yes, there are some, so rename them and loop
222              traceRn (sep [ptext SLIT("Slurped"), int (length inst_decls), ptext SLIT("instance decls")])
223                                                                 `thenRn_`
224              mapRn (rn_inst_decl compulsory_mode) inst_decls    `thenRn` \ new_inst_decls ->
225              slurp_compulsories (new_inst_decls ++ decls1)
226 \end{code}
227
228 \begin{code}
229 closeDecls :: RnSMode
230            -> [RenamedHsDecl]                   -- Declarations got so far
231            -> RnMG [RenamedHsDecl]              -- input + extra decls slurped
232         -- The monad includes a list of possibly-unresolved Names
233         -- This list is empty when closeDecls returns
234
235 closeDecls mode decls 
236   = popOccurrenceName mode              `thenRn` \ maybe_unresolved ->
237     case maybe_unresolved of
238
239         -- No more unresolved names
240         Nothing -> returnRn decls
241                         
242         -- An unresolved name
243         Just name_w_loc
244           ->    -- Slurp its declaration, if any
245 --           traceRn (sep [ptext SLIT("Considering"), ppr name_w_loc])  `thenRn_`
246              importDecl name_w_loc mode         `thenRn` \ maybe_decl ->
247              case maybe_decl of
248
249                 -- No declaration... (wired in thing or optional)
250                 Nothing   -> closeDecls mode decls
251
252                 -- Found a declaration... rename it
253                 Just decl -> rn_iface_decl mod_name mode decl   `thenRn` \ new_decl ->
254                              closeDecls mode (new_decl : decls)
255                          where
256                            mod_name = nameModule (fst name_w_loc)
257
258 rn_iface_decl mod_name mode decl
259   = initRnMS emptyRnEnv mod_name mode (rnDecl decl)
260                                         
261 rn_inst_decl mode (mod_name,decl)      = rn_iface_decl mod_name mode (InstD decl)
262 rn_data_decl mode (tycon_name,ty_decl) = rn_iface_decl mod_name mode (TyD ty_decl)
263                                        where
264                                          mod_name = nameModule tycon_name
265 \end{code}
266
267 \begin{code}
268 reportUnusedNames (ExportEnv export_avails _) explicit_info
269   | not (opt_WarnUnusedBinds || opt_WarnUnusedImports)
270   = returnRn ()
271
272   | otherwise
273   = getSlurpedNames                     `thenRn` \ slurped_names ->
274     let
275         unused_info :: FiniteMap Name HowInScope
276         unused_info = foldl delListFromFM
277                             (delListFromFM explicit_info (nameSetToList slurped_names))
278                             (map availNames export_avails)
279         unused_list = fmToList unused_info
280
281         groups = filter wanted (equivClasses cmp unused_list)
282                where
283                  (name1, his1) `cmp` (name2, his2) = his1 `cmph` his2
284                  
285                  (FromLocalDefn _)     `cmph` (FromImportDecl _ _)  = LT
286                  (FromLocalDefn _)     `cmph` (FromLocalDefn _)     = EQ
287                  (FromImportDecl m1 _) `cmph` (FromImportDecl m2 _) = m1 `compare` m2
288                  h1                    `cmph` h2                    = GT
289
290         wanted ((_,FromImportDecl _ _) : _) = opt_WarnUnusedImports
291         wanted ((_,FromLocalDefn _)    : _) = opt_WarnUnusedImports
292
293         pp_imp = sep [text "Warning: the following are unused:",
294                       nest 4 (vcat (map pp_group groups))]
295
296         pp_group group = sep [msg <> char ':',
297                               nest 4 (sep (map (pprOccName . nameOccName . fst) group))]
298                        where
299                          his = case group of
300                                   ((_,his) : _) -> his
301
302                          msg = case his of
303                                   FromImportDecl m _ -> text "Imported from" <+> pprModule m
304                                   FromLocalDefn _    -> text "Locally defined"   
305
306     in
307     if null groups
308     then returnRn ()
309     else addWarnRn pp_imp
310
311 rnStats :: [RenamedHsDecl] -> RnMG ()
312 rnStats all_decls
313         | opt_D_show_rn_trace || 
314           opt_D_show_rn_stats ||
315           opt_D_dump_rn 
316         = getRnStats all_decls          `thenRn` \ msg ->
317           ioToRnMG (printErrs msg)      `thenRn_`
318           returnRn ()
319
320         | otherwise = returnRn ()
321 \end{code}
322