[project @ 1999-02-10 14:39:19 by simonpj]
[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         ( 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, 
27                           warnUnusedTopNames
28                         )
29 import Name             ( Name, isLocallyDefined,
30                           NamedThing(..), ImportReason(..), Provenance(..),
31                           nameModule, pprModule, pprOccName, nameOccName,
32                           getNameProvenance, occNameUserString, 
33                         )
34 import RdrName          ( RdrName )
35 import NameSet
36 import TyCon            ( TyCon )
37 import PrelMods         ( mAIN, pREL_MAIN )
38 import TysWiredIn       ( unitTyCon, intTyCon, doubleTyCon )
39 import PrelInfo         ( ioTyCon_NAME, thinAirIdNames )
40 import Type             ( funTyCon )
41 import ErrUtils         ( pprBagOfErrors, pprBagOfWarnings,
42                           doIfSet, dumpIfSet, ghcExit
43                         )
44 import Bag              ( isEmptyBag )
45 import FiniteMap        ( fmToList, delListFromFM )
46 import UniqSupply       ( UniqSupply )
47 import Util             ( equivClasses )
48 import Maybes           ( maybeToBool )
49 import Outputable
50 \end{code}
51
52
53
54 \begin{code}
55 renameModule :: UniqSupply
56              -> RdrNameHsModule
57              -> IO (Maybe 
58                       ( RenamedHsModule   -- Output, after renaming
59                       , InterfaceDetails  -- Interface; for interface file generatino
60                       , RnNameSupply      -- Final env; for renaming derivings
61                       , [Module]          -- Imported modules; for profiling
62                       ))
63
64 renameModule us this_mod@(HsModule mod_name vers exports imports local_decls loc)
65   =     -- Initialise the renamer monad
66     initRn mod_name us (mkSearchPath opt_HiMap) loc
67            (rename this_mod)                            >>=
68         \ (maybe_rn_stuff, rn_errs_bag, rn_warns_bag) ->
69
70         -- Check for warnings
71     doIfSet (not (isEmptyBag rn_warns_bag))
72             (printErrs (pprBagOfWarnings rn_warns_bag)) >>
73
74         -- Check for errors; exit if so
75     doIfSet (not (isEmptyBag rn_errs_bag))
76             (printErrs (pprBagOfErrors rn_errs_bag)      >>
77              ghcExit 1
78             )                                            >>
79
80         -- Dump output, if any
81     (case maybe_rn_stuff of
82         Nothing  -> return ()
83         Just results@(rn_mod, _, _, _)
84                  -> dumpIfSet opt_D_dump_rn "Renamer:"
85                               (ppr rn_mod)
86     )                                                   >>
87
88         -- Return results
89     return maybe_rn_stuff
90 \end{code}
91
92
93 \begin{code}
94 rename this_mod@(HsModule mod_name vers exports imports local_decls loc)
95   =     -- FIND THE GLOBAL NAME ENVIRONMENT
96     getGlobalNames this_mod                     `thenRn` \ maybe_stuff ->
97
98         -- CHECK FOR EARLY EXIT
99     if not (maybeToBool maybe_stuff) then
100         -- Everything is up to date; no need to recompile further
101         rnStats []              `thenRn_`
102         returnRn Nothing
103     else
104     let
105         Just (export_env, rn_env, global_avail_env) = maybe_stuff
106     in
107
108         -- RENAME THE SOURCE
109     initRnMS rn_env SourceMode (
110         addImplicits mod_name                           `thenRn_`
111         rnSourceDecls local_decls
112     )                                                   `thenRn` \ (rn_local_decls, fvs) ->
113
114         -- SLURP IN ALL THE NEEDED DECLARATIONS
115     slurpDecls rn_local_decls           `thenRn` \ rn_all_decls ->
116
117         -- EXIT IF ERRORS FOUND
118     checkErrsRn                         `thenRn` \ no_errs_so_far ->
119     if not no_errs_so_far then
120         -- Found errors already, so exit now
121         rnStats []              `thenRn_`
122         returnRn Nothing
123     else
124
125         -- GENERATE THE VERSION/USAGE INFO
126     getImportVersions mod_name exports                  `thenRn` \ import_versions ->
127     getNameSupplyRn                                     `thenRn` \ name_supply ->
128
129         -- REPORT UNUSED NAMES
130     reportUnusedNames rn_env global_avail_env
131                       export_env
132                       fvs                               `thenRn_`
133
134         -- GENERATE THE SPECIAL-INSTANCE MODULE LIST
135         -- The "special instance" modules are those modules that contain instance
136         -- declarations that contain no type constructor or class that was declared
137         -- in that module.
138     getSpecialInstModules                               `thenRn` \ imported_special_inst_mods ->
139     let
140         special_inst_decls = [d | InstD d@(InstDecl inst_ty _ _ _ _) <- rn_local_decls,
141                                   all (not.isLocallyDefined) (nameSetToList (extractHsTyNames inst_ty))
142                              ]
143         special_inst_mods | null special_inst_decls = imported_special_inst_mods
144                           | otherwise               = mod_name : imported_special_inst_mods
145     in
146                   
147     
148         -- RETURN THE RENAMED MODULE
149     let
150         import_mods = [mod | ImportDecl mod _ _ _ _ <- imports]
151
152         renamed_module = HsModule mod_name vers 
153                                   trashed_exports trashed_imports
154                                   rn_all_decls
155                                   loc
156     in
157     rnStats rn_all_decls        `thenRn_`
158     returnRn (Just (renamed_module, 
159                     (import_versions, export_env, special_inst_mods),
160                      name_supply,
161                      import_mods))
162   where
163     trashed_exports  = {-trace "rnSource:trashed_exports"-} Nothing
164     trashed_imports  = {-trace "rnSource:trashed_imports"-} []
165 \end{code}
166
167 @addImplicits@ forces the renamer to slurp in some things which aren't
168 mentioned explicitly, but which might be needed by the type checker.
169
170 \begin{code}
171 addImplicits mod_name
172   = addImplicitOccsRn (implicit_main ++ default_tys ++ thinAirIdNames)
173   where
174         -- Add occurrences for Int, Double, and (), because they
175         -- are the types to which ambigious type variables may be defaulted by
176         -- the type checker; so they won't always appear explicitly.
177         -- [The () one is a GHC extension for defaulting CCall results.]
178         -- ALSO: funTyCon, since it occurs implicitly everywhere!
179         --       (we don't want to be bothered with addImplicitOcc at every
180         --        function application)
181     default_tys = [getName intTyCon, getName doubleTyCon,
182                    getName unitTyCon, getName funTyCon]
183
184         -- Add occurrences for IO or PrimIO
185     implicit_main |  mod_name == mAIN
186                   || mod_name == pREL_MAIN = [ioTyCon_NAME]
187                   |  otherwise             = []
188 \end{code}
189
190
191 \begin{code}
192 slurpDecls decls
193   =     -- First of all, get all the compulsory decls
194     slurp_compulsories decls    `thenRn` \ decls1 ->
195
196         -- Next get the optional ones
197     closeDecls optional_mode decls1     `thenRn` \ decls2 ->
198
199         -- Finally get those deferred data type declarations
200     getDeferredDataDecls                                `thenRn` \ data_decls ->
201     mapRn (rn_data_decl compulsory_mode) data_decls     `thenRn` \ rn_data_decls ->
202
203         -- Done
204     returnRn (rn_data_decls ++ decls2)
205
206   where
207     compulsory_mode = InterfaceMode Compulsory
208     optional_mode   = InterfaceMode Optional
209
210         -- The "slurp_compulsories" function is a loop that alternates
211         -- between slurping compulsory decls and slurping the instance
212         -- decls thus made relavant.
213         -- We *must* loop again here.  Why?  Two reasons:
214         -- (a) an instance decl will give rise to an unresolved dfun, whose
215         --      decl we must slurp to get its version number; that's the version
216         --      number for the whole instance decl.  (And its unfolding might mention new
217         --  unresolved names.)
218         -- (b) an instance decl might give rise to a new unresolved class,
219         --      whose decl we must slurp, which might let in some new instance decls,
220         --      and so on.  Example:  instance Foo a => Baz [a] where ...
221     slurp_compulsories decls
222       = closeDecls compulsory_mode decls        `thenRn` \ decls1 ->
223         
224                 -- Instance decls still pending?
225         getImportedInstDecls                    `thenRn` \ inst_decls ->
226         if null inst_decls then 
227                 -- No, none
228             returnRn decls1
229         else
230                 -- Yes, there are some, so rename them and loop
231              traceRn (sep [ptext SLIT("Slurped"), int (length inst_decls), ptext SLIT("instance decls")])
232                                                                 `thenRn_`
233              mapRn (rn_inst_decl compulsory_mode) inst_decls    `thenRn` \ new_inst_decls ->
234              slurp_compulsories (new_inst_decls ++ decls1)
235 \end{code}
236
237 \begin{code}
238 closeDecls :: RnMode
239            -> [RenamedHsDecl]                   -- Declarations got so far
240            -> RnMG [RenamedHsDecl]              -- input + extra decls slurped
241         -- The monad includes a list of possibly-unresolved Names
242         -- This list is empty when closeDecls returns
243
244 closeDecls mode decls 
245   = popOccurrenceName mode              `thenRn` \ maybe_unresolved ->
246     case maybe_unresolved of
247
248         -- No more unresolved names
249         Nothing -> returnRn decls
250                         
251         -- An unresolved name
252         Just name_w_loc
253           ->    -- Slurp its declaration, if any
254 --           traceRn (sep [ptext SLIT("Considering"), ppr name_w_loc])  `thenRn_`
255              importDecl name_w_loc mode         `thenRn` \ maybe_decl ->
256              case maybe_decl of
257
258                 -- No declaration... (wired in thing or optional)
259                 Nothing   -> closeDecls mode decls
260
261                 -- Found a declaration... rename it
262                 Just decl -> rn_iface_decl mod_name mode decl   `thenRn` \ new_decl ->
263                              closeDecls mode (new_decl : decls)
264                          where
265                            mod_name = nameModule (fst name_w_loc)
266
267 rn_iface_decl mod_name mode decl
268   = setModuleRn mod_name $
269     initRnMS emptyRnEnv mode (rnIfaceDecl decl)
270                                         
271 rn_inst_decl mode (mod_name,decl)    = rn_iface_decl mod_name mode (InstD decl)
272 rn_data_decl mode (mod_name,ty_decl) = rn_iface_decl mod_name mode (TyClD ty_decl)
273 \end{code}
274
275 \begin{code}
276 reportUnusedNames (RnEnv gbl_env _) avail_env (ExportEnv export_avails _) mentioned_names
277   | not (opt_WarnUnusedBinds || opt_WarnUnusedImports)
278   = returnRn ()
279
280   | otherwise
281   = let
282         used_names = mentioned_names `unionNameSets` availsToNameSet export_avails
283
284         -- Now, a use of C implies a use of T,
285         -- if C was brought into scope by T(..) or T(C)
286         really_used_names = used_names `unionNameSets`
287                             mkNameSet [ availName avail 
288                                       | sub_name <- nameSetToList used_names,
289                                         let avail = case lookupNameEnv avail_env sub_name of
290                                                         Just avail -> avail
291                                                         Nothing -> pprTrace "r.u.n" (ppr sub_name) $
292                                                                    Avail sub_name
293                                       ]
294
295         defined_names = mkNameSet (concat (rdrEnvElts gbl_env))
296         defined_but_not_used = nameSetToList (defined_names `minusNameSet` really_used_names)
297
298         -- Filter out the ones only defined implicitly
299         bad_guys = filter reportableUnusedName defined_but_not_used
300     in
301     warnUnusedTopNames bad_guys `thenRn_`
302     returnRn ()
303
304 reportableUnusedName :: Name -> Bool
305 reportableUnusedName name
306   = explicitlyImported (getNameProvenance name) && 
307     not (startsWithUnderscore (occNameUserString (nameOccName name)))
308   where
309     explicitlyImported (LocalDef _ _)                        = True     -- Report unused defns of local vars
310     explicitlyImported (NonLocalDef (UserImport _ _ expl) _) = expl     -- Report unused explicit imports
311     explicitlyImported other                                 = False    -- Don't report others
312    
313         -- Haskell 98 encourages compilers to suppress warnings about
314         -- unused names in a pattern if they start with "_".
315     startsWithUnderscore ('_' : _) = True       -- Suppress warnings for names starting
316     startsWithUnderscore other     = False      -- with an underscore
317
318 rnStats :: [RenamedHsDecl] -> RnMG ()
319 rnStats all_decls
320         | opt_D_show_rn_trace || 
321           opt_D_show_rn_stats ||
322           opt_D_dump_rn 
323         = getRnStats all_decls          `thenRn` \ msg ->
324           ioToRnMG (printErrs msg)      `thenRn_`
325           returnRn ()
326
327         | otherwise = returnRn ()
328 \end{code}
329