2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
13 #include "HsVersions.h"
15 import CmdLineOpts ( opt_D_dump_tc, opt_D_dump_deriv )
16 import HsSyn ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..) )
17 import RnHsSyn ( RenamedHsModule )
18 import TcHsSyn ( TcMonoBinds, TypecheckedMonoBinds, zonkTopBinds,
19 TypecheckedForeignDecl, zonkForeignExports
23 import Inst ( Inst, emptyLIE, plusLIE )
24 import TcBinds ( tcTopBindsAndThen )
25 import TcClassDcl ( tcClassDecls2 )
26 import TcDefaults ( tcDefaults )
27 import TcEnv ( TcIdOcc(..), tcExtendGlobalValEnv, tcExtendTyConEnv,
28 getEnv_TyCons, getEnv_Classes, tcLookupLocalValue,
29 lookupGlobalByKey, tcSetGlobalValEnv,
30 tcLookupTyCon, initEnv, GlobalValueEnv
32 import TcExpr ( tcId )
33 import TcForeign ( tcForeignImports, tcForeignExports )
34 import TcIfaceSig ( tcInterfaceSigs )
35 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
36 import TcInstUtil ( buildInstanceEnvs, classDataCon, InstInfo )
37 import TcSimplify ( tcSimplifyTop )
38 import TcTyClsDecls ( tcTyAndClassDecls1 )
39 import TcTyDecls ( mkDataBinds )
40 import TcType ( TcType, typeToTcType,
44 import RnMonad ( RnNameSupply )
45 import Bag ( isEmptyBag )
46 import ErrUtils ( ErrMsg,
47 pprBagOfErrors, dumpIfSet
49 import Id ( Id, idType )
50 import Name ( Name, nameUnique, isLocallyDefined, pprModule, NamedThing(..) )
51 import TyCon ( TyCon, tyConKind )
52 import DataCon ( dataConId )
53 import Class ( Class, classSelIds, classTyCon )
54 import Type ( mkTyConApp, Type )
55 import TysWiredIn ( unitTy )
56 import PrelMods ( mAIN )
57 import PrelInfo ( main_NAME, ioTyCon_NAME,
58 thinAirIdNames, setThinAirIds
60 import TcUnify ( unifyTauTy )
61 import Unique ( Unique )
62 import UniqSupply ( UniqSupply )
64 import Bag ( Bag, isEmptyBag )
70 Outside-world interface:
73 -- Convenient type synonyms first:
75 = (TypecheckedMonoBinds,
77 Bag InstInfo, -- Instance declaration information
78 [TypecheckedForeignDecl], -- foreign import & exports.
81 [Id] -- The thin-air Ids
84 type TcDDumpDeriv = SDoc
91 -> IO (Maybe TcResults)
93 typecheckModule us rn_name_supply mod
95 (maybe_result, warns, errs) =
96 initTc us initEnv (tcModule rn_name_supply mod)
101 dumpIfSet opt_D_dump_tc "Typechecked"
102 (case maybe_result of
103 Just (binds, _, _, _, _, _, _, _) -> ppr binds
104 Nothing -> text "Typecheck failed") >>
106 dumpIfSet opt_D_dump_deriv "Derived instances"
107 (case maybe_result of
108 Just (_, _, _, _, _, dump_deriv, _, _) -> dump_deriv
111 -- write the thin-air Id map
112 (case maybe_result of
113 Just (_, _, _, _, _, _, _, thin_air_ids) -> setThinAirIds thin_air_ids
117 return (if isEmptyBag errs then
123 | isEmptyBag errs = return ()
124 | otherwise = printErrs (pprBagOfErrors errs)
127 The internal monster:
129 tcModule :: RnNameSupply -- for renaming derivings
130 -> RenamedHsModule -- input
131 -> TcM s TcResults -- output
133 tcModule rn_name_supply
134 (HsModule mod_name verion exports imports fixities decls src_loc)
135 = tcAddSrcLoc src_loc $ -- record where we're starting
137 fixTc (\ ~(unf_env ,_) ->
138 -- unf_env is used for type-checking interface pragmas
139 -- which is done lazily [ie failure just drops the pragma
140 -- without having any global-failure effect].
142 -- unf_env is also used to get the pragam info
143 -- for imported dfuns and default methods
145 -- The knot for instance information. This isn't used at all
146 -- till we type-check value declarations
147 fixTc ( \ ~(rec_inst_mapper, _, _, _, _) ->
149 -- Type-check the type and class decls
150 -- trace "tcTyAndClassDecls:" $
151 tcTyAndClassDecls1 unf_env rec_inst_mapper decls `thenTc` \ env ->
154 -- Typecheck the instance decls, includes deriving
156 -- trace "tcInstDecls:" $
157 tcInstDecls1 unf_env decls mod_name rn_name_supply
158 ) `thenTc` \ (inst_info, deriv_binds, ddump_deriv) ->
161 buildInstanceEnvs inst_info `thenNF_Tc` \ inst_mapper ->
163 returnTc (inst_mapper, env, inst_info, deriv_binds, ddump_deriv)
165 -- End of inner fix loop
166 ) `thenTc` \ (_, env, inst_info, deriv_binds, ddump_deriv) ->
171 -- Default declarations
172 tcDefaults decls `thenTc` \ defaulting_tys ->
173 tcSetDefaultTys defaulting_tys $
175 -- Create any necessary record selector Ids and their bindings
176 -- "Necessary" includes data and newtype declarations
177 -- We don't create bindings for dictionary constructors;
178 -- they are always fully applied, and the bindings are just there
179 -- to support partial applications
181 tycons = getEnv_TyCons env
182 classes = getEnv_Classes env
183 local_tycons = filter isLocallyDefined tycons
184 local_classes = filter isLocallyDefined classes
186 mkDataBinds tycons `thenTc` \ (data_ids, data_binds) ->
188 -- Extend the global value environment with
190 -- (b) record selectors
191 -- (c) class op selectors
192 -- (d) default-method ids
193 tcExtendGlobalValEnv data_ids $
194 tcExtendGlobalValEnv (concat (map classSelIds classes)) $
196 -- Extend the TyCon envt with the tycons corresponding to
197 -- the classes, and the global value environment with the
198 -- corresponding data cons.
199 -- They are mentioned in types in interface files.
200 tcExtendGlobalValEnv (map (dataConId . classDataCon) classes) $
201 tcExtendTyConEnv [ (getName tycon, (kindToTcKind (tyConKind tycon), Nothing, tycon))
203 let tycon = classTyCon clas
206 -- Interface type signatures
207 -- We tie a knot so that the Ids read out of interfaces are in scope
208 -- when we read their pragmas.
209 -- What we rely on is that pragmas are typechecked lazily; if
210 -- any type errors are found (ie there's an inconsistency)
211 -- we silently discard the pragma
212 tcInterfaceSigs unf_env decls `thenTc` \ sig_ids ->
213 tcExtendGlobalValEnv sig_ids $
215 -- foreign import declarations next.
216 tcForeignImports decls `thenTc` \ (fo_ids, foi_decls) ->
217 tcExtendGlobalValEnv fo_ids $
219 -- Value declarations next.
220 -- We also typecheck any extra binds that came out of the "deriving" process
223 (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
224 (get_val_decls decls `ThenBinds` deriv_binds)
225 ( tcGetEnv `thenNF_Tc` \ env ->
226 -- tcGetUnique `thenNF_Tc` \ uniq ->
227 -- pprTrace "tc7" (ppr uniq) $
228 returnTc ((EmptyMonoBinds, env), emptyLIE)
229 ) `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
232 -- foreign export declarations next.
233 tcForeignExports decls `thenTc` \ (lie_fodecls, foe_binds, foe_decls) ->
235 -- Second pass over class and instance declarations,
236 -- to compile the bindings themselves.
237 -- pprTrace "tc8" emtpy $
238 tcInstDecls2 inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
239 tcClassDecls2 decls `thenNF_Tc` \ (lie_clasdecls, cls_binds) ->
241 -- Check that "main" has the right signature
242 tcCheckMainSig mod_name `thenTc_`
244 -- Deal with constant or ambiguous InstIds. How could
245 -- there be ambiguous ones? They can only arise if a
246 -- top-level decl falls under the monomorphism
247 -- restriction, and no subsequent decl instantiates its
248 -- type. (Usually, ambiguous type variables are resolved
249 -- during the generalisation step.)
251 lie_alldecls = lie_valdecls `plusLIE`
252 lie_instdecls `plusLIE`
253 lie_clasdecls `plusLIE`
256 tcSimplifyTop lie_alldecls `thenTc` \ const_inst_binds ->
259 -- Backsubstitution. This must be done last.
260 -- Even tcCheckMainSig and tcSimplifyTop may do some unification.
262 all_binds = data_binds `AndMonoBinds`
263 val_binds `AndMonoBinds`
264 inst_binds `AndMonoBinds`
265 cls_binds `AndMonoBinds`
266 const_inst_binds `AndMonoBinds`
269 zonkTopBinds all_binds `thenNF_Tc` \ (all_binds', really_final_env) ->
270 tcSetGlobalValEnv really_final_env $
271 zonkForeignExports foe_decls `thenNF_Tc` \ foe_decls' ->
274 thin_air_ids = map (lookupGlobalByKey really_final_env . nameUnique) thinAirIdNames
275 -- When looking up the thin-air names we must use
276 -- a global env that includes the zonked locally-defined Ids too
277 -- Hence using really_final_env
279 returnTc (really_final_env,
280 (all_binds', local_tycons, local_classes, inst_info,
281 foi_decls ++ foe_decls',
282 ddump_deriv, really_final_env, thin_air_ids))
284 -- End of outer fix loop
285 ) `thenTc` \ (final_env, stuff) ->
288 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
293 tcCheckMainSig mod_name
295 = returnTc () -- A non-main module
298 = -- Check that main is defined
299 tcLookupTyCon ioTyCon_NAME `thenTc` \ (_,_,ioTyCon) ->
300 tcLookupLocalValue main_NAME `thenNF_Tc` \ maybe_main_id ->
301 case maybe_main_id of {
302 Nothing -> failWithTc noMainErr ;
305 -- Check that it has the right type (or a more general one)
307 expected_tau = typeToTcType (mkTyConApp ioTyCon [unitTy])
309 tcId main_NAME `thenNF_Tc` \ (_, lie, main_tau) ->
310 tcSetErrCtxt mainTyCheckCtxt $
311 unifyTauTy expected_tau
313 checkTc (isEmptyBag lie) (mainTyMisMatch expected_tau (idType main_id))
318 = hsep [ptext SLIT("When checking that"), ppr main_NAME, ptext SLIT("has the required type")]
321 = hsep [ptext SLIT("Module"), quotes (pprModule mAIN),
322 ptext SLIT("must include a definition for"), quotes (ppr main_NAME)]
324 mainTyMisMatch :: TcType s -> TcType s -> ErrMsg
325 mainTyMisMatch expected actual
326 = hang (hsep [ppr main_NAME, ptext SLIT("has the wrong type")])
328 hsep [ptext SLIT("Expected:"), ppr expected],
329 hsep [ptext SLIT("Inferred:"), ppr actual]