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