[project @ 1996-07-25 20:43:49 by partain]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcModule.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcModule]{Typechecking a whole module}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module TcModule (
10         typecheckModule,
11         SYN_IE(TcResults),
12         SYN_IE(TcResultBinds),
13         SYN_IE(TcIfaceInfo),
14         SYN_IE(TcSpecialiseRequests),
15         SYN_IE(TcDDumpDeriv)
16     ) where
17
18 IMP_Ubiq(){-uitous-}
19
20 import HsSyn            ( HsModule(..), HsBinds(..), Bind, HsExpr,
21                           TyDecl, SpecDataSig, ClassDecl, InstDecl,
22                           SpecInstSig, DefaultDecl, Sig, Fake, InPat,
23                           FixityDecl, IE, ImportDecl
24                         )
25 import RnHsSyn          ( SYN_IE(RenamedHsModule), RenamedFixityDecl(..) )
26 import TcHsSyn          ( SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr),
27                           TcIdOcc(..), zonkBinds, zonkDictBinds )
28
29 import TcMonad          hiding ( rnMtoTcM )
30 import Inst             ( Inst, plusLIE )
31 import TcBinds          ( tcBindsAndThen )
32 import TcClassDcl       ( tcClassDecls2 )
33 import TcDefaults       ( tcDefaults )
34 import TcEnv            ( tcExtendGlobalValEnv, getEnv_LocalIds,
35                           getEnv_TyCons, getEnv_Classes,
36                           tcLookupLocalValueByKey, tcLookupTyConByKey )
37 import SpecEnv          ( SpecEnv )
38 import TcIfaceSig       ( tcInterfaceSigs )
39 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
40 import TcInstUtil       ( buildInstanceEnvs, InstInfo )
41 import TcSimplify       ( tcSimplifyTop )
42 import TcTyClsDecls     ( tcTyAndClassDecls1 )
43 import TcTyDecls        ( mkDataBinds )
44
45 import Bag              ( listToBag )
46 import Class            ( GenClass, classSelIds )
47 import ErrUtils         ( SYN_IE(Warning), SYN_IE(Error) )
48 import Id               ( idType, isMethodSelId, isTopLevId, GenId, SYN_IE(IdEnv), nullIdEnv )
49 import Maybes           ( catMaybes )
50 import Name             ( isLocallyDefined )
51 import Pretty
52 import RnUtils          ( SYN_IE(RnEnv) )
53 import TyCon            ( TyCon )
54 import Type             ( applyTyCon )
55 import TysWiredIn       ( unitTy, mkPrimIoTy )
56 import TyVar            ( SYN_IE(TyVarEnv), nullTyVarEnv )
57 import Unify            ( unifyTauTy )
58 import UniqFM           ( lookupUFM_Directly, lookupWithDefaultUFM_Directly,
59                           filterUFM, eltsUFM )
60 import Unique           ( iOTyConKey )
61 import Util
62
63 import FiniteMap        ( emptyFM, FiniteMap )
64 tycon_specs = emptyFM
65 \end{code}
66
67 Outside-world interface:
68 \begin{code}
69 -- Convenient type synonyms first:
70 type TcResults
71   = (TcResultBinds,
72      TcIfaceInfo,
73      TcSpecialiseRequests,
74      TcDDumpDeriv)
75
76 type TcResultBinds
77   = (TypecheckedHsBinds,        -- record selector binds
78      TypecheckedHsBinds,        -- binds from class decls; does NOT
79                                 -- include default-methods bindings
80      TypecheckedHsBinds,        -- binds from instance decls; INCLUDES
81                                 -- class default-methods binds
82      TypecheckedHsBinds,        -- binds from value decls
83
84      [(Id, TypecheckedHsExpr)]) -- constant instance binds
85
86 type TcIfaceInfo -- things for the interface generator
87   = ([Id], [TyCon], [Class], Bag InstInfo)
88
89 type TcSpecialiseRequests
90   = FiniteMap TyCon [(Bool, [Maybe Type])]
91     -- source tycon specialisation requests
92
93 type TcDDumpDeriv
94   = PprStyle -> Pretty
95
96 ---------------
97 typecheckModule
98         :: UniqSupply
99         -> RnEnv                -- for renaming derivings
100         -> RenamedHsModule
101         -> MaybeErr
102             (TcResults,         -- if all goes well...
103              Bag Warning)       -- (we can still get warnings)
104             (Bag Error,         -- if we had errors...
105              Bag Warning)
106
107 typecheckModule us rn_env mod
108   = initTc us (tcModule rn_env mod)
109 \end{code}
110
111 The internal monster:
112 \begin{code}
113 tcModule :: RnEnv               -- for renaming derivings
114          -> RenamedHsModule     -- input
115          -> TcM s TcResults     -- output
116
117 tcModule rn_env
118         (HsModule mod_name verion exports imports fixities
119                   ty_decls specdata_sigs cls_decls inst_decls specinst_sigs
120                   default_decls val_decls sigs src_loc)
121
122   = ASSERT(null imports)
123
124     tcAddSrcLoc src_loc $       -- record where we're starting
125
126         -- Tie the knot for inteface-file value declaration signatures
127         -- This info is only used inside the knot for type-checking the
128         -- pragmas, which is done lazily [ie failure just drops the pragma
129         -- without having any global-failure effect].
130
131     -- trace "tc1" $
132
133     fixTc (\ ~(_, _, _, _, _, _, sig_ids) ->
134
135         -- trace "tc2" $
136         tcExtendGlobalValEnv sig_ids (
137
138         -- The knot for instance information.  This isn't used at all
139         -- till we type-check value declarations
140         fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
141
142              -- Type-check the type and class decls
143             --trace "tcTyAndClassDecls:"        $
144             tcTyAndClassDecls1 rec_inst_mapper ty_decls_bag cls_decls_bag
145                                         `thenTc` \ env ->
146
147             --trace "tc3" $
148                 -- Typecheck the instance decls, includes deriving
149             tcSetEnv env (
150             --trace "tcInstDecls:"      $
151             tcInstDecls1 inst_decls_bag specinst_sigs
152                          mod_name rn_env fixities 
153             )                           `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
154
155             --trace "tc4" $
156             buildInstanceEnvs inst_info `thenTc` \ inst_mapper ->
157
158             returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
159
160         ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
161
162         --trace "tc5" $
163         tcSetEnv env (
164
165             -- Default declarations
166         tcDefaults default_decls        `thenTc` \ defaulting_tys ->
167         tcSetDefaultTys defaulting_tys  ( -- for the iface sigs...
168
169         -- Create any necessary record selector Ids and their bindings
170         -- "Necessary" includes data and newtype declarations
171         let
172                 tycons   = getEnv_TyCons env
173                 classes  = getEnv_Classes env
174         in
175         mkDataBinds tycons              `thenTc` \ (data_ids, data_binds) ->
176
177         -- Extend the global value environment with 
178         --      a) constructors
179         --      b) record selectors
180         --      c) class op selectors
181         tcExtendGlobalValEnv data_ids                           $
182         tcExtendGlobalValEnv (concat (map classSelIds classes)) $
183
184             -- Interface type signatures
185             -- We tie a knot so that the Ids read out of interfaces are in scope
186             --   when we read their pragmas.
187             -- What we rely on is that pragmas are typechecked lazily; if
188             --   any type errors are found (ie there's an inconsistency)
189             --   we silently discard the pragma
190         tcInterfaceSigs sigs            `thenTc` \ sig_ids ->
191         tcGetEnv                        `thenNF_Tc` \ env ->
192         --trace "tc6" $
193
194         returnTc (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, sig_ids)
195
196     )))) `thenTc` \ (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, _) ->
197
198     --trace "tc7" $
199     tcSetEnv env (                              -- to the end...
200     tcSetDefaultTys defaulting_tys (            -- ditto
201
202         -- Value declarations next.
203         -- We also typecheck any extra binds that came out of the "deriving" process
204     --trace "tcBinds:"                  $
205     tcBindsAndThen
206         (\ binds1 (binds2, thing) -> (binds1 `ThenBinds` binds2, thing))
207         (val_decls `ThenBinds` deriv_binds)
208         (       -- Second pass over instance declarations,
209                 -- to compile the bindings themselves.
210             --trace "tc8" $
211             tcInstDecls2  inst_info     `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
212             tcClassDecls2 cls_decls_bag `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
213             tcGetEnv                    `thenNF_Tc` \ env ->
214             returnTc ( (EmptyBinds, (inst_binds, cls_binds, env)),
215                        lie_instdecls `plusLIE` lie_clasdecls,
216                        () ))
217
218         `thenTc` \ ((val_binds, (inst_binds, cls_binds, final_env)), lie_alldecls, _) ->
219
220         -- Deal with constant or ambiguous InstIds.  How could
221         -- there be ambiguous ones?  They can only arise if a
222         -- top-level decl falls under the monomorphism
223         -- restriction, and no subsequent decl instantiates its
224         -- type.  (Usually, ambiguous type variables are resolved
225         -- during the generalisation step.)
226     --trace "tc9" $
227     tcSimplifyTop lie_alldecls                  `thenTc` \ const_insts ->
228
229         -- Backsubstitution.  Monomorphic top-level decls may have
230         -- been instantiated by subsequent decls, and the final
231         -- simplification step may have instantiated some
232         -- ambiguous types.  So, sadly, we need to back-substitute
233         -- over the whole bunch of bindings.
234         -- 
235         -- More horrible still, we have to do it in a careful order, so that
236         -- all the TcIds are in scope when we come across them.
237         -- 
238         -- These bindings ought really to be bundled together in a huge
239         -- recursive group, but HsSyn doesn't have recursion among Binds, only
240         -- among MonoBinds.  Sigh again.
241     zonkDictBinds nullTyVarEnv nullIdEnv const_insts    `thenNF_Tc` \ (const_insts', ve1) ->
242     zonkBinds nullTyVarEnv ve1 val_binds                `thenNF_Tc` \ (val_binds', ve2) ->
243
244     zonkBinds nullTyVarEnv ve2 data_binds       `thenNF_Tc` \ (data_binds', _) ->
245     zonkBinds nullTyVarEnv ve2 inst_binds       `thenNF_Tc` \ (inst_binds', _) ->
246     zonkBinds nullTyVarEnv ve2 cls_binds        `thenNF_Tc` \ (cls_binds', _) ->
247
248     let
249         localids = getEnv_LocalIds final_env
250         tycons   = getEnv_TyCons   final_env
251         classes  = getEnv_Classes  final_env
252
253         local_tycons  = filter isLocallyDefined tycons
254         local_classes = filter isLocallyDefined classes
255         local_vals    = [ v | v <- eltsUFM ve2, isLocallyDefined v && isTopLevId v ]
256                         -- the isTopLevId is doubtful...
257     in
258         -- FINISHED AT LAST
259     returnTc (
260         (data_binds', cls_binds', inst_binds', val_binds', const_insts'),
261
262              -- the next collection is just for mkInterface
263         (local_vals, local_tycons, local_classes, inst_info),
264
265         tycon_specs,
266
267         ddump_deriv
268     )))
269   where
270     ty_decls_bag   = listToBag ty_decls
271     cls_decls_bag  = listToBag cls_decls
272     inst_decls_bag = listToBag inst_decls
273 \end{code}