2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
8 typecheckModule, typecheckExpr, TcResults(..)
11 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlag(..), DynFlags, opt_PprStyle_Debug )
14 import HsSyn ( HsBinds(..), MonoBinds(..), HsDecl(..) )
15 import HsTypes ( toHsType )
16 import RnHsSyn ( RenamedHsDecl, RenamedHsExpr )
17 import TcHsSyn ( TypecheckedMonoBinds, TypecheckedHsExpr,
18 TypecheckedForeignDecl, TypecheckedRuleDecl,
19 zonkTopBinds, zonkForeignExports, zonkRules, mkHsLet
24 import TcType ( newTyVarTy )
25 import Inst ( plusLIE )
26 import TcBinds ( tcTopBinds )
27 import TcClassDcl ( tcClassDecls2, mkImplicitClassBinds )
28 import TcDefaults ( tcDefaults )
29 import TcExpr ( tcMonoExpr )
30 import TcEnv ( TcEnv, InstInfo(iDFunId), tcExtendGlobalValEnv,
31 tcEnvTyCons, tcEnvClasses, isLocalThing,
32 tcSetEnv, tcSetInstEnv, initTcEnv, getTcGEnv
34 import TcRules ( tcRules )
35 import TcForeign ( tcForeignImports, tcForeignExports )
36 import TcIfaceSig ( tcInterfaceSigs )
37 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
38 import TcSimplify ( tcSimplifyTop )
39 import TcTyClsDecls ( tcTyAndClassDecls )
40 import TcTyDecls ( mkImplicitDataBinds )
42 import CoreUnfold ( unfoldingTemplate )
43 import Type ( funResultTy, splitForAllTys, openTypeKind )
44 import Bag ( isEmptyBag )
45 import ErrUtils ( printErrorsAndWarnings, dumpIfSet_dyn, showPass )
46 import Id ( idType, idUnfolding )
47 import Module ( Module )
48 import Name ( Name, toRdrName )
49 import Name ( nameEnvElts, lookupNameEnv )
50 import TyCon ( tyConGenInfo )
52 import BasicTypes ( EP(..), Fixity )
53 import Bag ( isEmptyBag )
55 import HscTypes ( PersistentCompilerState(..), HomeSymbolTable,
56 PackageTypeEnv, DFunId, ModIface(..),
57 TypeEnv, extendTypeEnvList,
58 TyThing(..), mkTypeEnv )
59 import List ( partition )
62 Outside-world interface:
65 -- Convenient type synonyms first:
68 -- All these fields have info *just for this module*
69 tc_env :: TypeEnv, -- The top level TypeEnv
70 tc_insts :: [DFunId], -- Instances
71 tc_binds :: TypecheckedMonoBinds, -- Bindings
72 tc_fords :: [TypecheckedForeignDecl], -- Foreign import & exports.
73 tc_rules :: [TypecheckedRuleDecl] -- Transformation rules
79 -> PersistentCompilerState
81 -> ModIface -- Iface for this module
82 -> PrintUnqualified -- For error printing
84 -> IO (Maybe (PersistentCompilerState, TcResults))
85 -- The new PCS is Augmented with imported information,
86 -- (but not stuff from this module)
89 typecheckModule dflags pcs hst mod_iface unqual decls
90 = do { maybe_tc_result <- typecheck dflags pcs hst unqual $
91 tcModule pcs hst get_fixity this_mod decls
92 ; printTcDump dflags maybe_tc_result
93 ; return maybe_tc_result }
95 this_mod = mi_module mod_iface
96 fixity_env = mi_fixities mod_iface
98 get_fixity :: Name -> Maybe Fixity
99 get_fixity nm = lookupNameEnv fixity_env nm
102 typecheckExpr :: DynFlags
103 -> PersistentCompilerState
105 -> PrintUnqualified -- For error printing
107 -> IO (Maybe TypecheckedHsExpr)
109 typecheckExpr dflags pcs hst unqual expr
110 = typecheck dflags pcs hst unqual $
111 newTyVarTy openTypeKind `thenTc` \ ty ->
112 tcMonoExpr expr ty `thenTc` \ (expr', lie) ->
113 tcSimplifyTop lie `thenTc` \ binds ->
114 returnTc (mkHsLet binds expr')
117 typecheck :: DynFlags
118 -> PersistentCompilerState
120 -> PrintUnqualified -- For error printing
124 typecheck dflags pcs hst unqual thing_inside
125 = do { showPass dflags "Typechecker";
126 ; env <- initTcEnv hst (pcs_PTE pcs)
128 ; (maybe_tc_result, (warns,errs)) <- initTc dflags env thing_inside
130 ; printErrorsAndWarnings unqual (errs,warns)
132 ; if isEmptyBag errs then
133 return maybe_tc_result
139 The internal monster:
141 tcModule :: PersistentCompilerState
143 -> (Name -> Maybe Fixity)
146 -> TcM (PersistentCompilerState, TcResults)
148 tcModule pcs hst get_fixity this_mod decls
149 = -- Type-check the type and class decls
150 fixTc (\ ~(unf_env, _, _, _, _) ->
151 -- (unf_env :: RecTcEnv) is used for type-checking interface pragmas
152 -- which is done lazily [ie failure just drops the pragma
153 -- without having any global-failure effect].
155 -- unf_env is also used to get the pragama info
156 -- for imported dfuns and default methods
158 -- traceTc (text "Tc1") `thenNF_Tc_`
159 tcTyAndClassDecls unf_env decls `thenTc` \ env ->
162 classes = tcEnvClasses env
163 tycons = tcEnvTyCons env -- INCLUDES tycons derived from classes
166 -- Typecheck the instance decls, includes deriving
167 -- traceTc (text "Tc2") `thenNF_Tc_`
168 tcInstDecls1 (pcs_insts pcs) (pcs_PRS pcs)
169 hst unf_env get_fixity this_mod
170 tycons decls `thenTc` \ (new_pcs_insts, inst_env, local_inst_info, deriv_binds) ->
171 tcSetInstEnv inst_env $
173 -- Interface type signatures
174 -- We tie a knot so that the Ids read out of interfaces are in scope
175 -- when we read their pragmas.
176 -- What we rely on is that pragmas are typechecked lazily; if
177 -- any type errors are found (ie there's an inconsistency)
178 -- we silently discard the pragma
179 -- We must do this before mkImplicitDataBinds (which comes next), since
180 -- the latter looks up unpackCStringId, for example, which is usually
182 -- traceTc (text "Tc3") `thenNF_Tc_`
183 tcInterfaceSigs unf_env decls `thenTc` \ sig_ids ->
184 tcExtendGlobalValEnv sig_ids $
186 -- Create any necessary record selector Ids and their bindings
187 -- "Necessary" includes data and newtype declarations
188 -- We don't create bindings for dictionary constructors;
189 -- they are always fully applied, and the bindings are just there
190 -- to support partial applications
191 mkImplicitDataBinds this_mod tycons `thenTc` \ (data_ids, imp_data_binds) ->
192 mkImplicitClassBinds this_mod classes `thenNF_Tc` \ (cls_ids, imp_cls_binds) ->
194 -- Extend the global value environment with
196 -- (b) record selectors
197 -- (c) class op selectors
198 -- (d) default-method ids... where? I can't see where these are
199 -- put into the envt, and I'm worried that the zonking phase
200 -- will find they aren't there and complain.
201 tcExtendGlobalValEnv data_ids $
202 tcExtendGlobalValEnv cls_ids $
203 tcGetEnv `thenTc` \ unf_env ->
204 returnTc (unf_env, new_pcs_insts, local_inst_info, deriv_binds,
205 imp_data_binds `AndMonoBinds` imp_cls_binds)
206 ) `thenTc` \ (env, new_pcs_insts, local_inst_info, deriv_binds, data_cls_binds) ->
210 -- Foreign import declarations next
211 -- traceTc (text "Tc4") `thenNF_Tc_`
212 tcForeignImports decls `thenTc` \ (fo_ids, foi_decls) ->
213 tcExtendGlobalValEnv fo_ids $
215 -- Default declarations
216 tcDefaults decls `thenTc` \ defaulting_tys ->
217 tcSetDefaultTys defaulting_tys $
219 -- Value declarations next.
220 -- We also typecheck any extra binds that came out of the "deriving" process
221 -- traceTc (text "Tc5") `thenNF_Tc_`
222 tcTopBinds (get_binds decls `ThenBinds` deriv_binds) `thenTc` \ ((val_binds, env), lie_valdecls) ->
225 -- Foreign export declarations next
226 -- traceTc (text "Tc6") `thenNF_Tc_`
227 tcForeignExports decls `thenTc` \ (lie_fodecls, foe_binds, foe_decls) ->
229 -- Second pass over class and instance declarations,
230 -- to compile the bindings themselves.
231 -- traceTc (text "Tc7") `thenNF_Tc_`
232 tcInstDecls2 local_inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
233 -- traceTc (text "Tc8") `thenNF_Tc_`
234 tcClassDecls2 this_mod decls `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
235 tcRules (pcs_rules pcs) this_mod decls `thenNF_Tc` \ (new_pcs_rules, lie_rules, local_rules) ->
237 -- Deal with constant or ambiguous InstIds. How could
238 -- there be ambiguous ones? They can only arise if a
239 -- top-level decl falls under the monomorphism
240 -- restriction, and no subsequent decl instantiates its
241 -- type. (Usually, ambiguous type variables are resolved
242 -- during the generalisation step.)
244 lie_alldecls = lie_valdecls `plusLIE`
245 lie_instdecls `plusLIE`
246 lie_clasdecls `plusLIE`
247 lie_fodecls `plusLIE`
250 tcSimplifyTop lie_alldecls `thenTc` \ const_inst_binds ->
252 -- Backsubstitution. This must be done last.
253 -- Even tcSimplifyTop may do some unification.
255 all_binds = data_cls_binds `AndMonoBinds`
256 val_binds `AndMonoBinds`
257 inst_binds `AndMonoBinds`
258 cls_dm_binds `AndMonoBinds`
259 const_inst_binds `AndMonoBinds`
262 -- traceTc (text "Tc9") `thenNF_Tc_`
263 zonkTopBinds all_binds `thenNF_Tc` \ (all_binds', final_env) ->
265 -- zonkTopBinds puts all the top-level Ids into the tcGEnv
266 zonkForeignExports foe_decls `thenNF_Tc` \ foe_decls' ->
267 zonkRules local_rules `thenNF_Tc` \ local_rules' ->
270 let (local_things, imported_things) = partition (isLocalThing this_mod)
271 (nameEnvElts (getTcGEnv final_env))
273 local_type_env :: TypeEnv
274 local_type_env = mkTypeEnv local_things
276 new_pte :: PackageTypeEnv
277 new_pte = extendTypeEnvList (pcs_PTE pcs) imported_things
279 final_pcs :: PersistentCompilerState
280 final_pcs = pcs { pcs_PTE = new_pte,
281 pcs_insts = new_pcs_insts,
282 pcs_rules = new_pcs_rules
285 -- traceTc (text "Tc10") `thenNF_Tc_`
287 TcResults { tc_env = local_type_env,
288 tc_binds = all_binds',
289 tc_insts = map iDFunId local_inst_info,
290 tc_fords = foi_decls ++ foe_decls',
291 tc_rules = local_rules'
295 get_binds decls = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
300 %************************************************************************
302 \subsection{Dumping output}
304 %************************************************************************
307 printTcDump dflags Nothing = return ()
308 printTcDump dflags (Just (_, results))
309 = do dumpIfSet_dyn dflags Opt_D_dump_types
310 "Type signatures" (dump_sigs results)
311 dumpIfSet_dyn dflags Opt_D_dump_tc
312 "Typechecked" (dump_tc results)
315 = vcat [ppr (tc_binds results),
316 pp_rules (tc_rules results),
317 ppr_gen_tycons [tc | ATyCon tc <- nameEnvElts (tc_env results)]
320 dump_sigs results -- Print type signatures
321 = -- Convert to HsType so that we get source-language style printing
322 -- And sort by RdrName
323 vcat $ map ppr_sig $ sortLt lt_sig $
324 [ (toRdrName id, toHsType (idType id))
325 | AnId id <- nameEnvElts (tc_env results),
329 lt_sig (n1,_) (n2,_) = n1 < n2
330 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
332 want_sig id | opt_PprStyle_Debug = True
333 | otherwise = True -- For now
335 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
336 vcat (map ppr_gen_tycon tcs),
340 -- x&y are now Id's, not CoreExpr's
342 | Just ep <- tyConGenInfo tycon
343 = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
345 | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
348 = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
349 ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
350 ptext SLIT("To:") <+> ppr (unfoldingTemplate (idUnfolding to))
353 (_,from_tau) = splitForAllTys (idType from)
356 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
357 nest 4 (vcat (map ppr rs)),