[project @ 1999-01-14 17:58:41 by sof]
[ghc-hetmet.git] / ghc / compiler / rename / Rename.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-1998
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         ( rnIfaceDecl, rnSourceDecls )
22 import RnIfaces         ( getImportedInstDecls, importDecl, getImportVersions, getSpecialInstModules,
23                           getDeferredDataDecls,
24                           mkSearchPath, getSlurpedNames, getRnStats
25                         )
26 import RnEnv            ( addImplicitOccsRn, availName, availNames, availsToNameSet, warnUnusedTopNames )
27 import Name             ( Name, isLocallyDefined,
28                           NamedThing(..), ImportReason(..), Provenance(..),
29                           nameModule, pprModule, pprOccName, nameOccName,
30                           getNameProvenance
31                         )
32 import NameSet
33 import TyCon            ( TyCon )
34 import PrelMods         ( mAIN, pREL_MAIN )
35 import TysWiredIn       ( unitTyCon, intTyCon, doubleTyCon )
36 import PrelInfo         ( ioTyCon_NAME, thinAirIdNames )
37 import ErrUtils         ( pprBagOfErrors, pprBagOfWarnings,
38                           doIfSet, dumpIfSet, ghcExit
39                         )
40 import Bag              ( isEmptyBag )
41 import FiniteMap        ( fmToList, delListFromFM )
42 import UniqSupply       ( UniqSupply )
43 import Util             ( equivClasses )
44 import Maybes           ( maybeToBool )
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 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 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, global_avail_env) = maybe_stuff
102     in
103
104         -- RENAME THE SOURCE
105     initRnMS rn_env mod_name SourceMode (
106         addImplicits mod_name                           `thenRn_`
107         rnSourceDecls local_decls
108     )                                                   `thenRn` \ (rn_local_decls, fvs) ->
109
110         -- SLURP IN ALL THE NEEDED DECLARATIONS
111     slurpDecls 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 rn_env global_avail_env
127                       export_env
128                       fvs                               `thenRn_`
129
130         -- GENERATE THE SPECIAL-INSTANCE MODULE LIST
131         -- The "special instance" modules are those modules that contain instance
132         -- declarations that contain no type constructor or class that was declared
133         -- in that module.
134     getSpecialInstModules                               `thenRn` \ imported_special_inst_mods ->
135     let
136         special_inst_decls = [d | InstD d@(InstDecl inst_ty _ _ _ _) <- rn_local_decls,
137                                   all (not.isLocallyDefined) (nameSetToList (extractHsTyNames inst_ty))
138                              ]
139         special_inst_mods | null special_inst_decls = imported_special_inst_mods
140                           | otherwise               = mod_name : imported_special_inst_mods
141     in
142                   
143     
144         -- RETURN THE RENAMED MODULE
145     let
146         import_mods = [mod | ImportDecl mod _ _ _ _ _ <- imports]
147
148         renamed_module = HsModule mod_name vers 
149                                   trashed_exports trashed_imports
150                                   rn_all_decls
151                                   loc
152     in
153     rnStats rn_all_decls        `thenRn_`
154     returnRn (Just (renamed_module, 
155                     (import_versions, export_env, special_inst_mods),
156                      name_supply,
157                      import_mods))
158   where
159     trashed_exports  = {-trace "rnSource:trashed_exports"-} Nothing
160     trashed_imports  = {-trace "rnSource:trashed_imports"-} []
161 \end{code}
162
163 @addImplicits@ forces the renamer to slurp in some things which aren't
164 mentioned explicitly, but which might be needed by the type checker.
165
166 \begin{code}
167 addImplicits mod_name
168   = addImplicitOccsRn (implicit_main ++ default_tys ++ thinAirIdNames)
169   where
170         -- Add occurrences for Int, Double, and (), because they
171         -- are the types to which ambigious type variables may be defaulted by
172         -- the type checker; so they won't always appear explicitly.
173         -- [The () one is a GHC extension for defaulting CCall results.]
174     default_tys = [getName intTyCon, getName doubleTyCon, getName unitTyCon ]
175
176         -- Add occurrences for IO or PrimIO
177     implicit_main |  mod_name == mAIN
178                   || mod_name == pREL_MAIN = [ioTyCon_NAME]
179                   |  otherwise             = []
180 \end{code}
181
182
183 \begin{code}
184 slurpDecls decls
185   =     -- First of all, get all the compulsory decls
186     slurp_compulsories decls    `thenRn` \ decls1 ->
187
188         -- Next get the optional ones
189     closeDecls optional_mode decls1     `thenRn` \ decls2 ->
190
191         -- Finally get those deferred data type declarations
192     getDeferredDataDecls                                `thenRn` \ data_decls ->
193     mapRn (rn_data_decl compulsory_mode) data_decls     `thenRn` \ rn_data_decls ->
194
195         -- Done
196     returnRn (rn_data_decls ++ decls2)
197
198   where
199     compulsory_mode = InterfaceMode Compulsory
200     optional_mode   = InterfaceMode Optional
201
202         -- The "slurp_compulsories" function is a loop that alternates
203         -- between slurping compulsory decls and slurping the instance
204         -- decls thus made relavant.
205         -- We *must* loop again here.  Why?  Two reasons:
206         -- (a) an instance decl will give rise to an unresolved dfun, whose
207         --      decl we must slurp to get its version number; that's the version
208         --      number for the whole instance decl.  (And its unfolding might mention new
209         --  unresolved names.)
210         -- (b) an instance decl might give rise to a new unresolved class,
211         --      whose decl we must slurp, which might let in some new instance decls,
212         --      and so on.  Example:  instance Foo a => Baz [a] where ...
213     slurp_compulsories decls
214       = closeDecls compulsory_mode decls        `thenRn` \ decls1 ->
215         
216                 -- Instance decls still pending?
217         getImportedInstDecls                    `thenRn` \ inst_decls ->
218         if null inst_decls then 
219                 -- No, none
220             returnRn decls1
221         else
222                 -- Yes, there are some, so rename them and loop
223              traceRn (sep [ptext SLIT("Slurped"), int (length inst_decls), ptext SLIT("instance decls")])
224                                                                 `thenRn_`
225              mapRn (rn_inst_decl compulsory_mode) inst_decls    `thenRn` \ new_inst_decls ->
226              slurp_compulsories (new_inst_decls ++ decls1)
227 \end{code}
228
229 \begin{code}
230 closeDecls :: RnSMode
231            -> [RenamedHsDecl]                   -- Declarations got so far
232            -> RnMG [RenamedHsDecl]              -- input + extra decls slurped
233         -- The monad includes a list of possibly-unresolved Names
234         -- This list is empty when closeDecls returns
235
236 closeDecls mode decls 
237   = popOccurrenceName mode              `thenRn` \ maybe_unresolved ->
238     case maybe_unresolved of
239
240         -- No more unresolved names
241         Nothing -> returnRn decls
242                         
243         -- An unresolved name
244         Just name_w_loc
245           ->    -- Slurp its declaration, if any
246 --           traceRn (sep [ptext SLIT("Considering"), ppr name_w_loc])  `thenRn_`
247              importDecl name_w_loc mode         `thenRn` \ maybe_decl ->
248              case maybe_decl of
249
250                 -- No declaration... (wired in thing or optional)
251                 Nothing   -> closeDecls mode decls
252
253                 -- Found a declaration... rename it
254                 Just decl -> rn_iface_decl mod_name mode decl   `thenRn` \ new_decl ->
255                              closeDecls mode (new_decl : decls)
256                          where
257                            mod_name = nameModule (fst name_w_loc)
258
259 rn_iface_decl mod_name mode decl
260   = initRnMS emptyRnEnv mod_name mode (rnIfaceDecl decl)
261                                         
262 rn_inst_decl mode (mod_name,decl)    = rn_iface_decl mod_name mode (InstD decl)
263 rn_data_decl mode (mod_name,ty_decl) = rn_iface_decl mod_name mode (TyClD ty_decl)
264 \end{code}
265
266 \begin{code}
267 reportUnusedNames (RnEnv gbl_env _) avail_env (ExportEnv export_avails _) mentioned_names
268   | not (opt_WarnUnusedBinds || opt_WarnUnusedImports)
269   = returnRn ()
270
271   | otherwise
272   = let
273         used_names = mentioned_names `unionNameSets` availsToNameSet export_avails
274
275         -- Now, a use of C implies a use of T,
276         -- if C was brought into scope by T(..) or T(C)
277         really_used_names = used_names `unionNameSets`
278                             mkNameSet [ availName avail 
279                                       | sub_name <- nameSetToList used_names,
280                                         let avail = case lookupNameEnv avail_env sub_name of
281                                                         Just avail -> avail
282                                                         Nothing -> pprTrace "r.u.n" (ppr sub_name) $
283                                                                    Avail sub_name
284                                       ]
285
286         defined_names = mkNameSet (concat (rdrEnvElts gbl_env))
287         defined_but_not_used = defined_names `minusNameSet` really_used_names
288
289         -- Filter out the ones only defined implicitly or whose OccNames
290         -- start with an '_', which we won't report.
291         bad_guys = filter is_explicit (nameSetToList defined_but_not_used)
292         is_explicit n = case getNameProvenance n of
293                           LocalDef _ _                              -> True
294                           NonLocalDef (UserImport _ _ explicit) _ _ -> explicit
295                           other                                     -> False
296   
297         -- Now group by whether locally defined or imported; 
298         -- one group is the locally-defined ones, one group per import module
299         groups = equivClasses cmp bad_guys
300                where
301                  name1 `cmp` name2 = getNameProvenance name1 `cmph` getNameProvenance name2
302                  
303                  cmph (LocalDef _ _) (NonLocalDef _ _ _)    = LT
304                  cmph (LocalDef _ _) (LocalDef _ _)         = EQ
305                  cmph (NonLocalDef (UserImport m1 _ _) _ _)
306                       (NonLocalDef (UserImport m2 _ _) _ _)
307                       = m1 `compare` m2
308                  cmph (NonLocalDef _ _ _) (LocalDef _ _)    = GT
309                         -- In-scope NonLocalDefs must have UserImport info on them
310
311         -- ToDo: report somehow on T(..) things where no constructors
312         -- are imported
313     in
314     mapRn warnUnusedTopNames groups     `thenRn_`
315     returnRn ()
316
317 rnStats :: [RenamedHsDecl] -> RnMG ()
318 rnStats all_decls
319         | opt_D_show_rn_trace || 
320           opt_D_show_rn_stats ||
321           opt_D_dump_rn 
322         = getRnStats all_decls          `thenRn` \ msg ->
323           ioToRnMG (printErrs msg)      `thenRn_`
324           returnRn ()
325
326         | otherwise = returnRn ()
327 \end{code}
328