2fab42ef494c55d109610b243db356cc1513eed8
[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,
30                           NamedThing(..),
31                            nameModule, pprModule, pprOccName, nameOccName
32                         )
33 import TysWiredIn       ( unitTyCon, intTyCon, doubleTyCon )
34 import TyCon            ( TyCon )
35 import PrelMods         ( mAIN, pREL_MAIN )
36 import PrelInfo         ( ioTyCon_NAME )
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 List             ( partition )
46 import Outputable
47 \end{code}
48
49
50
51 \begin{code}
52 renameModule :: UniqSupply
53              -> RdrNameHsModule
54              -> IO (Maybe 
55                       ( RenamedHsModule   -- Output, after renaming
56                       , InterfaceDetails  -- Interface; for interface file generatino
57                       , RnNameSupply      -- Final env; for renaming derivings
58                       , [Module]          -- Imported modules; for profiling
59                       ))
60
61 renameModule us this_mod@(HsModule mod_name vers exports imports fixities local_decls loc)
62   =     -- Initialise the renamer monad
63     initRn mod_name us (mkSearchPath opt_HiMap) loc
64            (rename this_mod)                            >>=
65         \ (maybe_rn_stuff, rn_errs_bag, rn_warns_bag) ->
66
67         -- Check for warnings
68     doIfSet (not (isEmptyBag rn_warns_bag))
69             (printErrs (pprBagOfWarnings rn_warns_bag)) >>
70
71         -- Check for errors; exit if so
72     doIfSet (not (isEmptyBag rn_errs_bag))
73             (printErrs (pprBagOfErrors rn_errs_bag)      >>
74              ghcExit 1
75             )                                            >>
76
77         -- Dump output, if any
78     (case maybe_rn_stuff of
79         Nothing  -> return ()
80         Just results@(rn_mod, _, _, _)
81                  -> dumpIfSet opt_D_dump_rn "Renamer:"
82                               (ppr rn_mod)
83     )                                                   >>
84
85         -- Return results
86     return maybe_rn_stuff
87 \end{code}
88
89
90 \begin{code}
91 rename this_mod@(HsModule mod_name vers exports imports fixities local_decls loc)
92   =     -- FIND THE GLOBAL NAME ENVIRONMENT
93     getGlobalNames this_mod                     `thenRn` \ maybe_stuff ->
94
95         -- CHECK FOR EARLY EXIT
96     if not (maybeToBool maybe_stuff) then
97         -- Everything is up to date; no need to recompile further
98         rnStats []              `thenRn_`
99         returnRn Nothing
100     else
101     let
102         Just (export_env, rn_env, explicit_info, print_unqual) = maybe_stuff
103     in
104
105         -- RENAME THE SOURCE
106     initRnMS rn_env mod_name SourceMode (
107         addImplicits mod_name                           `thenRn_`
108         mapRn rnDecl local_decls
109     )                                                   `thenRn` \ rn_local_decls ->
110
111         -- SLURP IN ALL THE NEEDED DECLARATIONS
112     slurpDecls print_unqual rn_local_decls              `thenRn` \ rn_all_decls ->
113
114         -- EXIT IF ERRORS FOUND
115     checkErrsRn                         `thenRn` \ no_errs_so_far ->
116     if not no_errs_so_far then
117         -- Found errors already, so exit now
118         rnStats []              `thenRn_`
119         returnRn Nothing
120     else
121
122         -- GENERATE THE VERSION/USAGE INFO
123     getImportVersions mod_name exports                  `thenRn` \ import_versions ->
124     getNameSupplyRn                                     `thenRn` \ name_supply ->
125
126         -- REPORT UNUSED NAMES
127     reportUnusedNames export_env explicit_info          `thenRn_`
128
129         -- GENERATE THE SPECIAL-INSTANCE MODULE LIST
130         -- The "special instance" modules are those modules that contain instance
131         -- declarations that contain no type constructor or class that was declared
132         -- in that module.
133     getSpecialInstModules                               `thenRn` \ imported_special_inst_mods ->
134     let
135         special_inst_decls = [d | InstD d@(InstDecl inst_ty _ _ _ _) <- rn_local_decls,
136                                   all (not.isLocallyDefined) (nameSetToList (extractHsTyNames inst_ty))
137                              ]
138         special_inst_mods | null special_inst_decls = imported_special_inst_mods
139                           | otherwise               = mod_name : imported_special_inst_mods
140     in
141                   
142     
143         -- RETURN THE RENAMED MODULE
144     let
145         import_mods = [mod | ImportDecl mod _ _ _ _ _ <- imports]
146
147         renamed_module = HsModule mod_name vers 
148                                   trashed_exports trashed_imports trashed_fixities
149                                   rn_all_decls
150                                   loc
151     in
152     rnStats rn_all_decls        `thenRn_`
153     returnRn (Just (renamed_module, 
154                     (import_versions, export_env, special_inst_mods),
155                      name_supply,
156                      import_mods))
157   where
158     trashed_exports  = {-trace "rnSource:trashed_exports"-} Nothing
159     trashed_imports  = {-trace "rnSource:trashed_imports"-} []
160     trashed_fixities = []
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)
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 every 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 print_unqual 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 print_unqual
200     optional_mode   = InterfaceMode Optional   print_unqual
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 (rnDecl decl)
261                                         
262 rn_inst_decl mode (mod_name,decl)      = rn_iface_decl mod_name mode (InstD decl)
263 rn_data_decl mode (tycon_name,ty_decl) = rn_iface_decl mod_name mode (TyD ty_decl)
264                                        where
265                                          mod_name = nameModule tycon_name
266 \end{code}
267
268 \begin{code}
269 reportUnusedNames (ExportEnv export_avails _) explicit_info
270   | not (opt_WarnUnusedBinds || opt_WarnUnusedImports)
271   = returnRn ()
272
273   | otherwise
274   = getSlurpedNames                     `thenRn` \ slurped_names ->
275     let
276         unused_info :: FiniteMap Name HowInScope
277         unused_info = foldl delListFromFM
278                             (delListFromFM explicit_info (nameSetToList slurped_names))
279                             (map availNames export_avails)
280         unused_list = fmToList unused_info
281
282         groups = filter wanted (equivClasses cmp unused_list)
283                where
284                  (name1, his1) `cmp` (name2, his2) = his1 `cmph` his2
285                  
286                  (FromLocalDefn _)     `cmph` (FromImportDecl _ _)  = LT
287                  (FromLocalDefn _)     `cmph` (FromLocalDefn _)     = EQ
288                  (FromImportDecl m1 _) `cmph` (FromImportDecl m2 _) = m1 `compare` m2
289                  h1                    `cmph` h2                    = GT
290
291         wanted ((_,FromImportDecl _ _) : _) = opt_WarnUnusedImports
292         wanted ((_,FromLocalDefn _)    : _) = opt_WarnUnusedImports
293
294         pp_imp = sep [text "Warning: the following are unused:",
295                       nest 4 (vcat (map pp_group groups))]
296
297         pp_group group = sep [msg <> char ':',
298                               nest 4 (sep (map (pprOccName . nameOccName . fst) group))]
299                        where
300                          his = case group of
301                                   ((_,his) : _) -> his
302
303                          msg = case his of
304                                   FromImportDecl m _ -> text "Imported from" <+> pprModule m
305                                   FromLocalDefn _    -> text "Locally defined"   
306
307     in
308     if null groups
309     then returnRn ()
310     else addWarnRn pp_imp
311
312 rnStats :: [RenamedHsDecl] -> RnMG ()
313 rnStats all_decls
314         | opt_D_show_rn_trace || 
315           opt_D_show_rn_stats ||
316           opt_D_dump_rn 
317         = getRnStats all_decls          `thenRn` \ msg ->
318           ioToRnMG (printErrs msg)      `thenRn_`
319           returnRn ()
320
321         | otherwise = returnRn ()
322 \end{code}
323