2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcModule]{Typechecking a whole module}
7 #include "HsVersions.h"
12 SYN_IE(TcSpecialiseRequests),
18 import CmdLineOpts ( opt_D_dump_tc, opt_D_dump_deriv )
19 import HsSyn ( HsDecl(..), HsModule(..), HsBinds(..), HsExpr, MonoBinds(..),
20 TyDecl, SpecDataSig, ClassDecl, InstDecl, IfaceSig,
21 SpecInstSig, DefaultDecl, Sig, Fake, InPat,
22 SYN_IE(RecFlag), nonRecursive, GRHSsAndBinds, Match,
23 FixityDecl, IE, ImportDecl, OutPat
25 import RnHsSyn ( SYN_IE(RenamedHsModule), RenamedFixityDecl(..) )
26 import TcHsSyn ( SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr),
27 SYN_IE(TypecheckedDictBinds), SYN_IE(TcMonoBinds),
28 SYN_IE(TypecheckedMonoBinds),
32 import Inst ( Inst, emptyLIE, plusLIE )
33 import TcBinds ( tcBindsAndThen )
34 import TcClassDcl ( tcClassDecls2 )
35 import TcDefaults ( tcDefaults )
36 import TcEnv ( tcExtendGlobalValEnv, getEnv_LocalIds,
37 getEnv_TyCons, getEnv_Classes, tcLookupLocalValue,
38 tcLookupLocalValueByKey, tcLookupTyCon,
39 tcLookupGlobalValueByKeyMaybe )
40 import SpecEnv ( SpecEnv )
41 import TcExpr ( tcId )
42 import TcIfaceSig ( tcInterfaceSigs )
43 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
44 import TcInstUtil ( buildInstanceEnvs, InstInfo )
45 import TcSimplify ( tcSimplifyTop )
46 import TcTyClsDecls ( tcTyAndClassDecls1 )
47 import TcTyDecls ( mkDataBinds )
48 import TcType ( TcIdOcc(..), SYN_IE(TcType), tcInstType )
49 import TcKind ( TcKind )
51 import RnMonad ( RnNameSupply(..) )
52 import Bag ( listToBag )
53 import ErrUtils ( SYN_IE(Warning), SYN_IE(Error),
54 pprBagOfErrors, dumpIfSet, ghcExit
56 import Id ( idType, GenId, SYN_IE(IdEnv), nullIdEnv )
57 import Maybes ( catMaybes, MaybeErr(..) )
58 import Name ( Name, isLocallyDefined, pprModule )
60 import TyCon ( TyCon, isSynTyCon )
61 import Class ( GenClass, SYN_IE(Class), classSelIds )
62 import Type ( applyTyCon, mkSynTy, SYN_IE(Type) )
63 import PprType ( GenType, GenTyVar )
64 import TysWiredIn ( unitTy )
65 import PrelMods ( gHC_MAIN, mAIN )
66 import PrelInfo ( main_NAME, mainPrimIO_NAME, ioTyCon_NAME, primIoTyCon_NAME )
67 import TyVar ( GenTyVar, SYN_IE(TyVarEnv), nullTyVarEnv )
68 import Unify ( unifyTauTy )
69 import UniqFM ( lookupUFM_Directly, lookupWithDefaultUFM_Directly,
71 import Unique ( Unique )
72 import UniqSupply ( UniqSupply )
74 import Bag ( Bag, isEmptyBag )
76 import FiniteMap ( emptyFM, FiniteMap )
78 import Outputable ( Outputable(..), PprStyle, printErrs, pprDumpStyle, pprErrorsStyle )
83 Outside-world interface:
85 --ToDo: put this in HsVersions
86 #if __GLASGOW_HASKELL__ >= 200
87 # define REAL_WORLD RealWorld
89 # define REAL_WORLD _RealWorld
93 -- Convenient type synonyms first:
95 = (TypecheckedMonoBinds,
97 Bag InstInfo, -- Instance declaration information
101 type TcSpecialiseRequests
102 = FiniteMap TyCon [(Bool, [Maybe Type])]
103 -- source tycon specialisation requests
113 -> IO (Maybe TcResults)
115 typecheckModule us rn_name_supply mod
116 = case initTc us (tcModule rn_name_supply mod) of
117 Failed (errs, warns) ->
122 Succeeded (results@(binds, _, _, _, _, dump_deriv), warns) ->
125 dumpIfSet opt_D_dump_tc "Typechecked"
126 (ppr pprDumpStyle binds) >>
128 dumpIfSet opt_D_dump_deriv "Derived instances"
129 (dump_deriv pprDumpStyle) >>
131 return (Just results)
134 | isEmptyBag errs = return ()
135 | otherwise = printErrs (pprBagOfErrors pprErrorsStyle errs)
138 The internal monster:
140 tcModule :: RnNameSupply -- for renaming derivings
141 -> RenamedHsModule -- input
142 -> TcM s TcResults -- output
144 tcModule rn_name_supply
145 (HsModule mod_name verion exports imports fixities decls src_loc)
146 = tcAddSrcLoc src_loc $ -- record where we're starting
148 fixTc (\ ~(unf_env ,_) ->
149 -- unf_env is used for type-checking interface pragmas
150 -- which is done lazily [ie failure just drops the pragma
151 -- without having any global-failure effect].
153 -- unf_env is also used to get the pragam info for dfuns.
155 -- The knot for instance information. This isn't used at all
156 -- till we type-check value declarations
157 fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
159 -- Type-check the type and class decls
160 -- trace "tcTyAndClassDecls:" $
161 tcTyAndClassDecls1 unf_env rec_inst_mapper decls `thenTc` \ env ->
164 -- Typecheck the instance decls, includes deriving
166 -- trace "tcInstDecls:" $
167 tcInstDecls1 unf_env decls mod_name rn_name_supply
168 ) `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
171 buildInstanceEnvs inst_info `thenTc` \ inst_mapper ->
173 returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
175 -- End of inner fix loop
176 ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
181 -- Default declarations
182 tcDefaults decls `thenTc` \ defaulting_tys ->
183 tcSetDefaultTys defaulting_tys $
185 -- Create any necessary record selector Ids and their bindings
186 -- "Necessary" includes data and newtype declarations
188 tycons = getEnv_TyCons env
189 classes = getEnv_Classes env
191 mkDataBinds tycons `thenTc` \ (data_ids, data_binds) ->
193 -- Extend the global value environment with
195 -- (b) record selectors
196 -- (c) class op selectors
197 -- (d) default-method ids
198 tcExtendGlobalValEnv data_ids $
199 tcExtendGlobalValEnv (concat (map classSelIds classes)) $
202 -- Interface type signatures
203 -- We tie a knot so that the Ids read out of interfaces are in scope
204 -- when we read their pragmas.
205 -- What we rely on is that pragmas are typechecked lazily; if
206 -- any type errors are found (ie there's an inconsistency)
207 -- we silently discard the pragma
208 tcInterfaceSigs unf_env decls `thenTc` \ sig_ids ->
209 tcExtendGlobalValEnv sig_ids $
212 -- Value declarations next.
213 -- We also typecheck any extra binds that came out of the "deriving" process
214 -- trace "tcBinds:" $
216 (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
217 (get_val_decls decls `ThenBinds` deriv_binds)
218 ( tcGetEnv `thenNF_Tc` \ env ->
219 returnTc ((EmptyMonoBinds, env), emptyLIE)
220 ) `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
224 -- Second pass over class and instance declarations,
225 -- to compile the bindings themselves.
227 tcInstDecls2 inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
228 tcClassDecls2 decls `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
232 -- Check that "main" has the right signature
233 tcCheckMainSig mod_name `thenTc_`
235 -- Deal with constant or ambiguous InstIds. How could
236 -- there be ambiguous ones? They can only arise if a
237 -- top-level decl falls under the monomorphism
238 -- restriction, and no subsequent decl instantiates its
239 -- type. (Usually, ambiguous type variables are resolved
240 -- during the generalisation step.)
243 lie_alldecls = lie_valdecls `plusLIE` lie_instdecls `plusLIE` lie_clasdecls
245 tcSimplifyTop lie_alldecls `thenTc` \ const_inst_binds ->
248 -- Backsubstitution. This must be done last.
249 -- Even tcCheckMainSig and tcSimplifyTop may do some unification.
251 all_binds = data_binds `AndMonoBinds`
252 val_binds `AndMonoBinds`
253 inst_binds `AndMonoBinds`
254 cls_binds `AndMonoBinds`
257 zonkTopBinds all_binds `thenNF_Tc` \ (all_binds', really_final_env) ->
259 returnTc (really_final_env, (all_binds', inst_info, ddump_deriv))
261 -- End of outer fix loop
262 ) `thenTc` \ (final_env, (all_binds', inst_info, ddump_deriv)) ->
266 tycons = getEnv_TyCons final_env
267 classes = getEnv_Classes final_env
269 local_tycons = filter isLocallyDefined tycons
270 local_classes = filter isLocallyDefined classes
276 local_tycons, local_classes, inst_info, tycon_specs,
281 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
286 tcCheckMainSig mod_name
287 | not is_main && not is_ghc_main
288 = returnTc () -- A non-main module
291 = -- Check that main is defined
292 tcLookupTyCon tycon_name `thenTc` \ (_,_,tycon) ->
293 tcLookupLocalValue main_name `thenNF_Tc` \ maybe_main_id ->
294 case maybe_main_id of {
295 Nothing -> failTc (noMainErr mod_name main_name);
298 -- Check that it has the right type (or a more general one)
300 expected_ty | isSynTyCon tycon = mkSynTy tycon [unitTy]
301 | otherwise = applyTyCon tycon [unitTy]
302 -- This is bizarre. There ought to be a suitable function in Type.lhs!
304 tcInstType [] expected_ty `thenNF_Tc` \ expected_tau ->
305 tcId main_name `thenNF_Tc` \ (_, lie, main_tau) ->
306 tcSetErrCtxt (mainTyCheckCtxt main_name) $
307 unifyTauTy expected_tau
309 checkTc (isEmptyBag lie) (mainTyMisMatch main_name expected_ty (idType main_id))
312 is_main = mod_name == mAIN
313 is_ghc_main = mod_name == gHC_MAIN
315 main_name | is_main = main_NAME
316 | otherwise = mainPrimIO_NAME
318 tycon_name | is_main = ioTyCon_NAME
319 | otherwise = primIoTyCon_NAME
321 mainTyCheckCtxt main_name sty
322 = hsep [ptext SLIT("When checking that"), ppr sty main_name, ptext SLIT("has the required type")]
324 noMainErr mod_name main_name sty
325 = hsep [ptext SLIT("Module"), pprModule sty mod_name,
326 ptext SLIT("must include a definition for"), ppr sty main_name]
328 mainTyMisMatch :: Name -> Type -> TcType s -> Error
329 mainTyMisMatch main_name expected actual sty
330 = hang (hsep [ppr sty main_name, ptext SLIT("has the wrong type")])
332 hsep [ptext SLIT("Expected:"), ppr sty expected],
333 hsep [ptext SLIT("Inferred:"), ppr sty actual]