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 ( tcTopBindsAndThen )
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 ( buildInstanceEnv, 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_binds :: TypecheckedMonoBinds,
75 tc_insts :: InstEnv, -- Instances, just for this module
76 tc_fords :: [TypecheckedForeignDecl], -- Foreign import & exports.
77 tc_rules :: [TypecheckedRuleDecl], -- Transformation rules
82 :: PersistentCompilerState
85 -> IO (Maybe (PersistentCompilerState, TcResults))
87 typecheckModule pcs hst mod
88 = do { us <- mkSplitUniqSupply 'a' ;
90 env <- initTcEnv global_symbol_table global_inst_env ;
92 (maybe_result, warns, errs) <- initTc us env (tcModule (pcsPRS pcs) mod)
94 printErrorsAndWarnings errs warns ;
96 case maybe_result of {
97 Nothing -> return Nothing ;
100 dumpIfSet opt_D_dump_types "Type signatures" (dump_sigs results) ;
101 dumpIfSet opt_D_dump_tc "Typechecked" (dump_tc results) ;
103 if isEmptyBag errs then
107 let groups :: FiniteMap Module TypeEnv
108 groups = groupTyThings (nameEnvElts (tc_env results))
110 local_type_env :: TypeEnv
111 local_type_env = lookupWithDefaultFM groups this_mod emptyNameEnv
113 new_pst :: PackageSymbolTable
114 new_pst = extendTypeEnv (pcsPST pcs) (delFromFM groups this_mod)
116 return (Just (pcs {pcsPST = new_pst},
117 results {tc_env = local_type_env}))
120 global_symbol_table = pcsPST pcs `plusModuleEnv` hst
122 global_inst_env = foldModuleEnv (plusInstEnv . instEnv) (pcsInsts pcs) gst
123 -- For now, make the total instance envt by simply
124 -- folding together all the instances we can find anywhere
127 The internal monster:
129 tcModule :: PersistentRenamerState
130 -> RenamedHsModule -- input
131 -> TcM TcResults -- output
133 tcModule prs (HsModule mod_name _ _ _ decls _ src_loc)
134 = tcAddSrcLoc src_loc $ -- record where we're starting
136 fixTc (\ ~(unf_env ,_) ->
137 -- (unf_env :: TcEnv) is used for type-checking interface pragmas
138 -- which is done lazily [ie failure just drops the pragma
139 -- without having any global-failure effect].
141 -- unf_env is also used to get the pragama info
142 -- for imported dfuns and default methods
144 -- Type-check the type and class decls
145 tcTyAndClassDecls unf_env decls `thenTc` \ env ->
148 -- Typecheck the instance decls, includes deriving
149 tcInstDecls1 prs unf_env decls
150 (mkThisModule mod_name) `thenTc` \ (inst_info, deriv_binds) ->
152 buildInstanceEnv inst_info `thenNF_Tc` \ inst_env ->
154 tcSetInstEnv inst_env $
156 classes = tcEnvClasses env
157 tycons = tcEnvTyCons env -- INCLUDES tycons derived from classes
158 local_classes = filter isLocallyDefined classes
159 local_tycons = [ tc | tc <- tycons,
161 not (isClassTyCon tc)
163 -- For local_tycons, filter out the ones derived from classes
164 -- Otherwise the latter show up in interface files
167 -- Default declarations
168 tcDefaults decls `thenTc` \ defaulting_tys ->
169 tcSetDefaultTys defaulting_tys $
171 -- Interface type signatures
172 -- We tie a knot so that the Ids read out of interfaces are in scope
173 -- when we read their pragmas.
174 -- What we rely on is that pragmas are typechecked lazily; if
175 -- any type errors are found (ie there's an inconsistency)
176 -- we silently discard the pragma
177 -- We must do this before mkImplicitDataBinds (which comes next), since
178 -- the latter looks up unpackCStringId, for example, which is usually
180 tcInterfaceSigs unf_env decls `thenTc` \ sig_ids ->
181 tcExtendGlobalValEnv sig_ids $
183 -- Create any necessary record selector Ids and their bindings
184 -- "Necessary" includes data and newtype declarations
185 -- We don't create bindings for dictionary constructors;
186 -- they are always fully applied, and the bindings are just there
187 -- to support partial applications
188 mkImplicitDataBinds tycons `thenTc` \ (data_ids, imp_data_binds) ->
189 mkImplicitClassBinds classes `thenNF_Tc` \ (cls_ids, imp_cls_binds) ->
191 -- Extend the global value environment with
193 -- (b) record selectors
194 -- (c) class op selectors
195 -- (d) default-method ids... where? I can't see where these are
196 -- put into the envt, and I'm worried that the zonking phase
197 -- will find they aren't there and complain.
198 tcExtendGlobalValEnv data_ids $
199 tcExtendGlobalValEnv cls_ids $
201 -- foreign import declarations next.
202 tcForeignImports decls `thenTc` \ (fo_ids, foi_decls) ->
203 tcExtendGlobalValEnv fo_ids $
205 -- Value declarations next.
206 -- We also typecheck any extra binds that came out of the "deriving" process
208 (\ is_rec binds1 (binds2, thing) -> (binds1 `AndMonoBinds` binds2, thing))
209 (get_val_decls decls `ThenBinds` deriv_binds)
210 ( tcGetEnv `thenNF_Tc` \ env ->
211 returnTc ((EmptyMonoBinds, env), emptyLIE)
212 ) `thenTc` \ ((val_binds, final_env), lie_valdecls) ->
215 -- foreign export declarations next.
216 tcForeignExports decls `thenTc` \ (lie_fodecls, foe_binds, foe_decls) ->
218 -- Second pass over class and instance declarations,
219 -- to compile the bindings themselves.
220 tcInstDecls2 inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
221 tcClassDecls2 decls `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
222 tcRules decls `thenNF_Tc` \ (lie_rules, rules) ->
225 -- Deal with constant or ambiguous InstIds. How could
226 -- there be ambiguous ones? They can only arise if a
227 -- top-level decl falls under the monomorphism
228 -- restriction, and no subsequent decl instantiates its
229 -- type. (Usually, ambiguous type variables are resolved
230 -- during the generalisation step.)
232 lie_alldecls = lie_valdecls `plusLIE`
233 lie_instdecls `plusLIE`
234 lie_clasdecls `plusLIE`
235 lie_fodecls `plusLIE`
238 tcSimplifyTop lie_alldecls `thenTc` \ const_inst_binds ->
240 -- Check that Main defines main
241 (if mod_name == mAIN_Name then
242 tcLookupGlobal_maybe mainName `thenNF_Tc` \ maybe_main ->
244 Just (AnId _) -> returnTc ()
245 other -> addErrTc noMainErr
250 -- Backsubstitution. This must be done last.
251 -- Even tcSimplifyTop may do some unification.
253 all_binds = imp_data_binds `AndMonoBinds`
254 imp_cls_binds `AndMonoBinds`
255 val_binds `AndMonoBinds`
256 inst_binds `AndMonoBinds`
257 cls_dm_binds `AndMonoBinds`
258 const_inst_binds `AndMonoBinds`
261 zonkTopBinds all_binds `thenNF_Tc` \ (all_binds', really_final_env) ->
262 tcSetEnv really_final_env $
263 -- zonkTopBinds puts all the top-level Ids into the tcGEnv
265 zonkForeignExports foe_decls `thenNF_Tc` \ foe_decls' ->
266 zonkRules rules `thenNF_Tc` \ rules' ->
268 returnTc (really_final_env,
269 (TcResults { tc_env = tcGEnv really_final_env,
270 tc_binds = all_binds',
271 tc_insts = inst_info,
272 tc_fords = foi_decls ++ foe_decls',
276 -- End of outer fix loop
277 ) `thenTc` \ (final_env, stuff) ->
280 get_val_decls decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
286 = hsep [ptext SLIT("Module"), quotes (pprModuleName mAIN_Name),
287 ptext SLIT("must include a definition for"), quotes (ptext SLIT("main"))]
291 %************************************************************************
293 \subsection{Dumping output}
295 %************************************************************************
299 = vcat [ppr (tc_binds results),
300 pp_rules (tc_rules results),
301 ppr_gen_tycons (tc_tycons results)
304 dump_sigs results -- Print type signatures
305 = -- Convert to HsType so that we get source-language style printing
306 -- And sort by RdrName
307 vcat $ map ppr_sig $ sortLt lt_sig $
308 [(toRdrName id, toHsType (idType id)) | id <- nameEnvElts (tc_env results),
312 lt_sig (n1,_) (n2,_) = n1 < n2
313 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
315 want_sig id | opt_PprStyle_Debug = True
316 | otherwise = isLocallyDefined n &&
318 not (isSysOcc (nameOccName n))
322 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
323 vcat (map ppr_gen_tycon (filter isLocallyDefined tcs)),
327 -- x&y are now Id's, not CoreExpr's
329 | Just ep <- tyConGenInfo tycon
330 = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
332 | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
335 = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
336 ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
337 ptext SLIT("To:") <+> ppr (unfoldingTemplate (idUnfolding to))
340 (_,from_tau) = splitForAllTys (idType from)
343 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
344 nest 4 (vcat (map ppr rs)),