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