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