077b0791ef2fe2765ec7a005ad8bca5a54713fae
[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     fixTc (\ ~(_, _, _, _, _, _, sig_ids) ->
132         tcExtendGlobalValEnv sig_ids (
133
134         -- The knot for instance information.  This isn't used at all
135         -- till we type-check value declarations
136         fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
137
138              -- Type-check the type and class decls
139             --trace "tcTyAndClassDecls:"        $
140             tcTyAndClassDecls1 rec_inst_mapper ty_decls_bag cls_decls_bag
141                                         `thenTc` \ env ->
142
143                 -- Typecheck the instance decls, includes deriving
144             tcSetEnv env (
145             --trace "tcInstDecls:"      $
146             tcInstDecls1 inst_decls_bag specinst_sigs
147                          mod_name rn_env fixities 
148             )                           `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
149
150             buildInstanceEnvs inst_info `thenTc` \ inst_mapper ->
151
152             returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
153
154         ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
155         tcSetEnv env (
156
157             -- Default declarations
158         tcDefaults default_decls        `thenTc` \ defaulting_tys ->
159         tcSetDefaultTys defaulting_tys  ( -- for the iface sigs...
160
161         -- Create any necessary record selector Ids and their bindings
162         -- "Necessary" includes data and newtype declarations
163         let
164                 tycons   = getEnv_TyCons env
165                 classes  = getEnv_Classes env
166         in
167         mkDataBinds tycons              `thenTc` \ (data_ids, data_binds) ->
168
169         -- Extend the global value environment with 
170         --      a) constructors
171         --      b) record selectors
172         --      c) class op selectors
173         tcExtendGlobalValEnv data_ids                           $
174         tcExtendGlobalValEnv (concat (map classSelIds classes)) $
175
176             -- Interface type signatures
177             -- We tie a knot so that the Ids read out of interfaces are in scope
178             --   when we read their pragmas.
179             -- What we rely on is that pragmas are typechecked lazily; if
180             --   any type errors are found (ie there's an inconsistency)
181             --   we silently discard the pragma
182         tcInterfaceSigs sigs            `thenTc` \ sig_ids ->
183         tcGetEnv                        `thenNF_Tc` \ env ->
184
185         returnTc (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, sig_ids)
186
187     )))) `thenTc` \ (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, _) ->
188
189     tcSetEnv env (                              -- to the end...
190     tcSetDefaultTys defaulting_tys (            -- ditto
191
192         -- Value declarations next.
193         -- We also typecheck any extra binds that came out of the "deriving" process
194     --trace "tcBinds:"                  $
195     tcBindsAndThen
196         (\ binds1 (binds2, thing) -> (binds1 `ThenBinds` binds2, thing))
197         (val_decls `ThenBinds` deriv_binds)
198         (       -- Second pass over instance declarations,
199                 -- to compile the bindings themselves.
200             tcInstDecls2  inst_info     `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
201             tcClassDecls2 cls_decls_bag `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
202             tcGetEnv                    `thenNF_Tc` \ env ->
203             returnTc ( (EmptyBinds, (inst_binds, cls_binds, env)),
204                        lie_instdecls `plusLIE` lie_clasdecls,
205                        () ))
206
207         `thenTc` \ ((val_binds, (inst_binds, cls_binds, final_env)), lie_alldecls, _) ->
208
209         -- Deal with constant or ambiguous InstIds.  How could
210         -- there be ambiguous ones?  They can only arise if a
211         -- top-level decl falls under the monomorphism
212         -- restriction, and no subsequent decl instantiates its
213         -- type.  (Usually, ambiguous type variables are resolved
214         -- during the generalisation step.)
215     tcSimplifyTop lie_alldecls                  `thenTc` \ const_insts ->
216
217         -- Backsubstitution.  Monomorphic top-level decls may have
218         -- been instantiated by subsequent decls, and the final
219         -- simplification step may have instantiated some
220         -- ambiguous types.  So, sadly, we need to back-substitute
221         -- over the whole bunch of bindings.
222         -- 
223         -- More horrible still, we have to do it in a careful order, so that
224         -- all the TcIds are in scope when we come across them.
225         -- 
226         -- These bindings ought really to be bundled together in a huge
227         -- recursive group, but HsSyn doesn't have recursion among Binds, only
228         -- among MonoBinds.  Sigh again.
229     zonkDictBinds nullTyVarEnv nullIdEnv const_insts    `thenNF_Tc` \ (const_insts', ve1) ->
230     zonkBinds nullTyVarEnv ve1 val_binds                `thenNF_Tc` \ (val_binds', ve2) ->
231
232     zonkBinds nullTyVarEnv ve2 data_binds       `thenNF_Tc` \ (data_binds', _) ->
233     zonkBinds nullTyVarEnv ve2 inst_binds       `thenNF_Tc` \ (inst_binds', _) ->
234     zonkBinds nullTyVarEnv ve2 cls_binds        `thenNF_Tc` \ (cls_binds', _) ->
235
236     let
237         localids = getEnv_LocalIds final_env
238         tycons   = getEnv_TyCons   final_env
239         classes  = getEnv_Classes  final_env
240
241         local_tycons  = filter isLocallyDefined tycons
242         local_classes = filter isLocallyDefined classes
243         local_vals    = [ v | v <- eltsUFM ve2, isLocallyDefined v && isTopLevId v ]
244                         -- the isTopLevId is doubtful...
245     in
246         -- FINISHED AT LAST
247     returnTc (
248         (data_binds', cls_binds', inst_binds', val_binds', const_insts'),
249
250              -- the next collection is just for mkInterface
251         (local_vals, local_tycons, local_classes, inst_info),
252
253         tycon_specs,
254
255         ddump_deriv
256     )))
257   where
258     ty_decls_bag   = listToBag ty_decls
259     cls_decls_bag  = listToBag cls_decls
260     inst_decls_bag = listToBag inst_decls
261 \end{code}