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