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