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