2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcModule]{Typechecking a whole module}
7 #include "HsVersions.h"
12 SYN_IE(TcResultBinds),
13 SYN_IE(TcSpecialiseRequests),
19 import HsSyn ( HsDecl(..), HsModule(..), HsBinds(..), Bind, HsExpr,
20 TyDecl, SpecDataSig, ClassDecl, InstDecl, IfaceSig,
21 SpecInstSig, DefaultDecl, Sig, Fake, InPat,
22 FixityDecl, IE, ImportDecl
24 import RnHsSyn ( SYN_IE(RenamedHsModule), RenamedFixityDecl(..) )
25 import TcHsSyn ( SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr),
26 TcIdOcc(..), zonkBinds, zonkDictBinds )
29 import Inst ( Inst, plusLIE )
30 import TcBinds ( tcBindsAndThen )
31 import TcClassDcl ( tcClassDecls2 )
32 import TcDefaults ( tcDefaults )
33 import TcEnv ( tcExtendGlobalValEnv, getEnv_LocalIds,
34 getEnv_TyCons, getEnv_Classes, tcLookupLocalValue,
35 tcLookupLocalValueByKey, tcLookupTyCon,
36 tcLookupGlobalValueByKeyMaybe )
37 import SpecEnv ( SpecEnv )
38 import TcExpr ( tcId )
39 import TcIfaceSig ( tcInterfaceSigs )
40 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
41 import TcInstUtil ( buildInstanceEnvs, InstInfo )
42 import TcSimplify ( tcSimplifyTop )
43 import TcTyClsDecls ( tcTyAndClassDecls1 )
44 import TcTyDecls ( mkDataBinds )
45 import TcType ( SYN_IE(TcType), tcInstType )
46 import TcKind ( TcKind )
48 import RnMonad ( RnNameSupply(..) )
49 import Bag ( listToBag )
50 import Class ( GenClass, classSelIds )
51 import ErrUtils ( SYN_IE(Warning), SYN_IE(Error) )
52 import Id ( idType, GenId, SYN_IE(IdEnv), nullIdEnv )
53 import Maybes ( catMaybes )
54 import Name ( Name, isLocallyDefined, pprModule )
56 import TyCon ( TyCon, isSynTyCon )
57 import Type ( applyTyCon, mkSynTy )
58 import PprType ( GenType, GenTyVar )
59 import TysWiredIn ( unitTy )
60 import PrelMods ( gHC_MAIN, mAIN )
61 import PrelInfo ( main_NAME, mainPrimIO_NAME, ioTyCon_NAME, primIoTyCon_NAME )
62 import TyVar ( GenTyVar, SYN_IE(TyVarEnv), nullTyVarEnv )
63 import Unify ( unifyTauTy )
64 import UniqFM ( lookupUFM_Directly, lookupWithDefaultUFM_Directly,
66 import Unique ( Unique )
68 import Bag ( Bag, isEmptyBag )
70 import FiniteMap ( emptyFM, FiniteMap )
74 Outside-world interface:
76 -- Convenient type synonyms first:
80 Bag InstInfo, -- Instance declaration information
85 = (TypecheckedHsBinds, -- record selector binds
86 TypecheckedHsBinds, -- binds from class decls; does NOT
87 -- include default-methods bindings
88 TypecheckedHsBinds, -- binds from instance decls; INCLUDES
89 -- class default-methods binds
90 TypecheckedHsBinds, -- binds from value decls
92 [(Id, TypecheckedHsExpr)]) -- constant instance binds
94 type TcSpecialiseRequests
95 = FiniteMap TyCon [(Bool, [Maybe Type])]
96 -- source tycon specialisation requests
107 (TcResults, -- if all goes well...
108 Bag Warning) -- (we can still get warnings)
109 (Bag Error, -- if we had errors...
112 typecheckModule us rn_name_supply mod
113 = initTc us (tcModule rn_name_supply mod)
116 The internal monster:
118 tcModule :: RnNameSupply -- for renaming derivings
119 -> RenamedHsModule -- input
120 -> TcM s TcResults -- output
122 tcModule rn_name_supply
123 (HsModule mod_name verion exports imports fixities decls src_loc)
124 = tcAddSrcLoc src_loc $ -- record where we're starting
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].
133 fixTc (\ ~(_, _, _, _, _, _, sig_ids) ->
136 tcExtendGlobalValEnv sig_ids (
138 -- The knot for instance information. This isn't used at all
139 -- till we type-check value declarations
140 fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
142 -- Type-check the type and class decls
143 -- trace "tcTyAndClassDecls:" $
144 tcTyAndClassDecls1 rec_inst_mapper decls `thenTc` \ env ->
147 -- Typecheck the instance decls, includes deriving
149 -- trace "tcInstDecls:" $
150 tcInstDecls1 decls mod_name rn_name_supply
151 ) `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
154 buildInstanceEnvs inst_info `thenTc` \ inst_mapper ->
156 returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
158 ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
163 -- Default declarations
164 tcDefaults decls `thenTc` \ defaulting_tys ->
165 tcSetDefaultTys defaulting_tys ( -- for the iface sigs...
167 -- Create any necessary record selector Ids and their bindings
168 -- "Necessary" includes data and newtype declarations
170 tycons = getEnv_TyCons env
171 classes = getEnv_Classes env
173 mkDataBinds tycons `thenTc` \ (data_ids, data_binds) ->
175 -- Extend the global value environment with
177 -- b) record selectors
178 -- c) class op selectors
179 tcExtendGlobalValEnv data_ids $
180 tcExtendGlobalValEnv (concat (map classSelIds classes)) $
182 -- Interface type signatures
183 -- We tie a knot so that the Ids read out of interfaces are in scope
184 -- when we read their pragmas.
185 -- What we rely on is that pragmas are typechecked lazily; if
186 -- any type errors are found (ie there's an inconsistency)
187 -- we silently discard the pragma
188 tcInterfaceSigs decls `thenTc` \ sig_ids ->
189 tcGetEnv `thenNF_Tc` \ env ->
192 returnTc (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, sig_ids)
194 )))) `thenTc` \ (env, inst_info, data_binds, deriv_binds, ddump_deriv, defaulting_tys, _) ->
197 tcSetEnv env ( -- to the end...
198 tcSetDefaultTys defaulting_tys ( -- ditto
200 -- Value declarations next.
201 -- We also typecheck any extra binds that came out of the "deriving" process
202 -- trace "tcBinds:" $
204 (\ binds1 (binds2, thing) -> (binds1 `ThenBinds` binds2, thing))
205 (get_val_decls decls `ThenBinds` deriv_binds)
206 ( -- Second pass over instance declarations,
207 -- to compile the bindings themselves.
209 tcInstDecls2 inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
210 tcClassDecls2 decls `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
211 tcCheckMainSig mod_name `thenTc_`
212 tcGetEnv `thenNF_Tc` \ env ->
213 returnTc ( (EmptyBinds, (inst_binds, cls_binds, env)),
214 lie_instdecls `plusLIE` lie_clasdecls,
217 `thenTc` \ ((val_binds, (inst_binds, cls_binds, final_env)), lie_alldecls, _) ->
219 -- Deal with constant or ambiguous InstIds. How could
220 -- there be ambiguous ones? They can only arise if a
221 -- top-level decl falls under the monomorphism
222 -- restriction, and no subsequent decl instantiates its
223 -- type. (Usually, ambiguous type variables are resolved
224 -- during the generalisation step.)
226 tcSimplifyTop lie_alldecls `thenTc` \ const_insts ->
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.
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.
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) ->
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', _) ->
249 localids = getEnv_LocalIds final_env
250 tycons = getEnv_TyCons final_env
251 classes = getEnv_Classes final_env
253 local_tycons = filter isLocallyDefined tycons
254 local_classes = filter isLocallyDefined classes
258 (data_binds', cls_binds', inst_binds', val_binds', const_insts'),
260 local_tycons, inst_info, tycon_specs,
265 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
270 tcCheckMainSig mod_name
271 | not is_main && not is_ghc_main
272 = returnTc () -- A non-main module
275 = -- Check that main is defined
276 tcLookupTyCon tycon_name `thenTc` \ (_,_,tycon) ->
277 tcLookupLocalValue main_name `thenNF_Tc` \ maybe_main_id ->
278 case maybe_main_id of {
279 Nothing -> failTc (noMainErr mod_name main_name);
282 -- Check that it has the right type (or a more general one)
284 expected_ty | isSynTyCon tycon = mkSynTy tycon [unitTy]
285 | otherwise = applyTyCon tycon [unitTy]
286 -- This is bizarre. There ought to be a suitable function in Type.lhs!
288 tcInstType [] expected_ty `thenNF_Tc` \ expected_tau ->
289 tcId main_name `thenNF_Tc` \ (_, lie, main_tau) ->
290 tcSetErrCtxt (mainTyCheckCtxt main_name) $
291 unifyTauTy expected_tau
293 checkTc (isEmptyBag lie) (mainTyMisMatch main_name expected_ty (idType main_id))
296 is_main = mod_name == mAIN
297 is_ghc_main = mod_name == gHC_MAIN
299 main_name | is_main = main_NAME
300 | otherwise = mainPrimIO_NAME
302 tycon_name | is_main = ioTyCon_NAME
303 | otherwise = primIoTyCon_NAME
305 mainTyCheckCtxt main_name sty
306 = ppCat [ppPStr SLIT("When checking that"), ppr sty main_name, ppPStr SLIT("has the required type")]
308 noMainErr mod_name main_name sty
309 = ppCat [ppPStr SLIT("Module"), pprModule sty mod_name,
310 ppPStr SLIT("must include a definition for"), ppr sty main_name]
312 mainTyMisMatch :: Name -> Type -> TcType s -> Error
313 mainTyMisMatch main_name expected actual sty
314 = ppHang (ppCat [ppr sty main_name, ppPStr SLIT("has the wrong type")])
316 ppCat [ppPStr SLIT("Expected:"), ppr sty expected],
317 ppCat [ppPStr SLIT("Inferred:"), ppr sty actual]