2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
12 #include "HsVersions.h"
14 import CmdLineOpts ( opt_D_dump_tc, opt_D_dump_types, opt_PprStyle_Debug )
15 import HsSyn ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..) )
16 import HsTypes ( toHsType )
17 import RnHsSyn ( RenamedHsModule )
18 import TcHsSyn ( TypecheckedMonoBinds,
19 TypecheckedForeignDecl, TypecheckedRuleDecl,
20 zonkTopBinds, zonkForeignExports, zonkRules
24 import Inst ( emptyLIE, plusLIE )
25 import TcBinds ( tcTopBinds )
26 import TcClassDcl ( tcClassDecls2, mkImplicitClassBinds )
27 import TcDefaults ( tcDefaults )
28 import TcEnv ( tcExtendGlobalValEnv, tcLookupGlobal_maybe,
29 tcEnvTyCons, tcEnvClasses,
30 tcSetEnv, tcSetInstEnv, initEnv
32 import TcRules ( tcRules )
33 import TcForeign ( tcForeignImports, tcForeignExports )
34 import TcIfaceSig ( tcInterfaceSigs )
35 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
36 import TcInstUtil ( InstInfo )
37 import TcSimplify ( tcSimplifyTop )
38 import TcTyClsDecls ( tcTyAndClassDecls )
39 import TcTyDecls ( mkImplicitDataBinds )
41 import CoreUnfold ( unfoldingTemplate )
42 import Type ( funResultTy, splitForAllTys )
43 import RnMonad ( RnNameSupply, FixityEnv )
44 import Bag ( isEmptyBag )
45 import ErrUtils ( printErrorsAndWarnings, dumpIfSet )
46 import Id ( idType, idName, idUnfolding )
47 import Module ( pprModuleName, mkThisModule, plusModuleEnv )
48 import Name ( nameOccName, isLocallyDefined, isGlobalName,
49 toRdrName, nameEnvElts,
51 import TyCon ( TyCon, isDataTyCon, tyConName, tyConGenInfo )
52 import OccName ( isSysOcc )
53 import TyCon ( TyCon, isClassTyCon )
54 import Class ( Class )
55 import PrelNames ( mAIN_Name, mainKey )
56 import UniqSupply ( UniqSupply )
57 import Maybes ( maybeToBool )
59 import BasicTypes ( EP(..) )
60 import Bag ( Bag, isEmptyBag )
65 Outside-world interface:
68 -- Convenient type synonyms first:
71 tc_pcs :: PersistentCompilerState, -- Augmented with imported information,
72 -- (but not stuff from this module)
73 tc_env :: TypeEnv, -- The TypeEnv just for the stuff from this module
74 tc_insts :: [DFunId], -- Instances, just for this module
75 tc_binds :: TypecheckedMonoBinds,
76 tc_fords :: [TypecheckedForeignDecl], -- Foreign import & exports.
77 tc_rules :: [TypecheckedRuleDecl], -- Transformation rules
82 :: PersistentCompilerState
85 -> IO (Maybe (PersistentCompilerState, TcResults))
87 typecheckModule pcs hst (HsModule mod_name _ _ _ decls _ src_loc)
88 = do { env <- initTcEnv global_symbol_table ;
90 (_, (maybe_result, msgs)) <- initTc env src_loc tc_module
92 printErrorsAndWarnings msgs ;
94 printTcDumps maybe_result ;
96 if isEmptyBag errs then
102 this_mod = mkThisModule
103 global_symbol_table = pcs_PST pcs `plusModuleEnv` hst
105 tc_module = fixTc (\ ~(unf_env ,_) -> tcModule pcs hst this_mod decls unf_env)
108 The internal monster:
110 tcModule :: PersistentCompilerState
114 -> TcEnv -- The knot-tied environment
117 -- (unf_env :: TcEnv) is used for type-checking interface pragmas
118 -- which is done lazily [ie failure just drops the pragma
119 -- without having any global-failure effect].
121 -- unf_env is also used to get the pragama info
122 -- for imported dfuns and default methods
124 tcModule pcs hst this_mod decls unf_env
125 = -- Type-check the type and class decls
126 tcTyAndClassDecls unf_env decls `thenTc` \ env ->
129 classes = tcEnvClasses env
130 tycons = tcEnvTyCons env -- INCLUDES tycons derived from classes
131 local_classes = filter isLocallyDefined classes
132 local_tycons = [ tc | tc <- tycons,
134 not (isClassTyCon tc)
136 -- For local_tycons, filter out the ones derived from classes
137 -- Otherwise the latter show up in interface files
140 -- Typecheck the instance decls, includes deriving
141 tcInstDecls1 pcs hst unf_env this_mod
142 local_tycons decls `thenTc` \ (pcs_with_insts, inst_env, inst_info, deriv_binds) ->
143 tcSetInstEnv inst_env $
145 -- Default declarations
146 tcDefaults decls `thenTc` \ defaulting_tys ->
147 tcSetDefaultTys defaulting_tys $
149 -- Interface type signatures
150 -- We tie a knot so that the Ids read out of interfaces are in scope
151 -- when we read their pragmas.
152 -- What we rely on is that pragmas are typechecked lazily; if
153 -- any type errors are found (ie there's an inconsistency)
154 -- we silently discard the pragma
155 -- We must do this before mkImplicitDataBinds (which comes next), since
156 -- the latter looks up unpackCStringId, for example, which is usually
158 tcInterfaceSigs unf_env decls `thenTc` \ sig_ids ->
159 tcExtendGlobalValEnv sig_ids $
161 -- Create any necessary record selector Ids and their bindings
162 -- "Necessary" includes data and newtype declarations
163 -- We don't create bindings for dictionary constructors;
164 -- they are always fully applied, and the bindings are just there
165 -- to support partial applications
166 mkImplicitDataBinds tycons `thenTc` \ (data_ids, imp_data_binds) ->
167 mkImplicitClassBinds classes `thenNF_Tc` \ (cls_ids, imp_cls_binds) ->
169 -- Extend the global value environment with
171 -- (b) record selectors
172 -- (c) class op selectors
173 -- (d) default-method ids... where? I can't see where these are
174 -- put into the envt, and I'm worried that the zonking phase
175 -- will find they aren't there and complain.
176 tcExtendGlobalValEnv data_ids $
177 tcExtendGlobalValEnv cls_ids $
179 -- Foreign import declarations next
180 tcForeignImports decls `thenTc` \ (fo_ids, foi_decls) ->
181 tcExtendGlobalValEnv fo_ids $
183 -- Value declarations next.
184 -- We also typecheck any extra binds that came out of the "deriving" process
185 tcTopBinds (get_binds decls `ThenBinds` deriv_binds) `thenTc` \ ((val_binds, env), lie_valdecls) ->
188 -- Foreign export declarations next
189 tcForeignExports decls `thenTc` \ (lie_fodecls, foe_binds, foe_decls) ->
191 -- Second pass over class and instance declarations,
192 -- to compile the bindings themselves.
193 tcInstDecls2 inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
194 tcClassDecls2 decls `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
195 tcRules decls `thenNF_Tc` \ (lie_rules, rules) ->
197 -- Deal with constant or ambiguous InstIds. How could
198 -- there be ambiguous ones? They can only arise if a
199 -- top-level decl falls under the monomorphism
200 -- restriction, and no subsequent decl instantiates its
201 -- type. (Usually, ambiguous type variables are resolved
202 -- during the generalisation step.)
204 lie_alldecls = lie_valdecls `plusLIE`
205 lie_instdecls `plusLIE`
206 lie_clasdecls `plusLIE`
207 lie_fodecls `plusLIE`
210 tcSimplifyTop lie_alldecls `thenTc` \ const_inst_binds ->
212 -- Check that Main defines main
213 checkMain this_mod `thenTc_`
215 -- Backsubstitution. This must be done last.
216 -- Even tcSimplifyTop may do some unification.
218 all_binds = imp_data_binds `AndMonoBinds`
219 imp_cls_binds `AndMonoBinds`
220 val_binds `AndMonoBinds`
221 inst_binds `AndMonoBinds`
222 cls_dm_binds `AndMonoBinds`
223 const_inst_binds `AndMonoBinds`
226 zonkTopBinds all_binds `thenNF_Tc` \ (all_binds', final_env) ->
228 -- zonkTopBinds puts all the top-level Ids into the tcGEnv
229 zonkForeignExports foe_decls `thenNF_Tc` \ foe_decls' ->
230 zonkRules rules `thenNF_Tc` \ rules' ->
233 let groups :: FiniteMap Module TypeEnv
234 groups = groupTyThings (nameEnvElts (tcGEnv final_env))
236 local_type_env :: TypeEnv
237 local_type_env = lookupWithDefaultFM groups this_mod emptyNameEnv
239 new_pst :: PackageSymbolTable
240 new_pst = extendTypeEnv (pcs_PST pcs) (delFromFM groups this_mod)
242 final_pcs :: PersistentCompilerState
243 final_pcs = pcs_with_insts {pcs_PST = new_pst}
245 returnTc (really_final_env,
246 TcResults { tc_pcs = final_pcs,
247 tc_env = local_type_env,
248 tc_binds = all_binds',
249 tc_insts = map instInfoDfunId inst_infos,
250 tc_fords = foi_decls ++ foe_decls',
254 get_binds decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
259 checkMain :: Module -> TcM ()
261 | moduleName this_mod == mAIN_Name
262 = tcLookupGlobal_maybe mainName `thenNF_Tc` \ maybe_main ->
264 Just (AnId _) -> returnTc ()
265 other -> addErrTc noMainErr
267 | otherwise = returnTc ()
270 = hsep [ptext SLIT("Module"), quotes (pprModuleName mAIN_Name),
271 ptext SLIT("must include a definition for"), quotes (ptext SLIT("main"))]
275 %************************************************************************
277 \subsection{Dumping output}
279 %************************************************************************
282 printTcDump Nothing = return ()
283 printTcDump (Just results)
284 = do { dumpIfSet opt_D_dump_types "Type signatures" (dump_sigs results) ;
285 dumpIfSet opt_D_dump_tc "Typechecked" (dump_tc results)
289 = vcat [ppr (tc_binds results),
290 pp_rules (tc_rules results),
291 ppr_gen_tycons (tc_tycons results)
294 dump_sigs results -- Print type signatures
295 = -- Convert to HsType so that we get source-language style printing
296 -- And sort by RdrName
297 vcat $ map ppr_sig $ sortLt lt_sig $
298 [(toRdrName id, toHsType (idType id)) | id <- nameEnvElts (tc_env results),
302 lt_sig (n1,_) (n2,_) = n1 < n2
303 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
305 want_sig id | opt_PprStyle_Debug = True
306 | otherwise = isLocallyDefined n &&
308 not (isSysOcc (nameOccName n))
312 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
313 vcat (map ppr_gen_tycon (filter isLocallyDefined tcs)),
317 -- x&y are now Id's, not CoreExpr's
319 | Just ep <- tyConGenInfo tycon
320 = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
322 | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
325 = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
326 ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
327 ptext SLIT("To:") <+> ppr (unfoldingTemplate (idUnfolding to))
330 (_,from_tau) = splitForAllTys (idType from)
333 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
334 nest 4 (vcat (map ppr rs)),