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 isIfaceRuleDecl, nullBinds, andMonoBindList
17 import HsTypes ( toHsType )
18 import RnHsSyn ( RenamedHsBinds, RenamedHsDecl, RenamedHsExpr )
19 import TcHsSyn ( TypecheckedMonoBinds, TypecheckedHsExpr,
20 TypecheckedForeignDecl, TypecheckedRuleDecl,
21 zonkTopBinds, zonkForeignExports, zonkRules, mkHsLet,
27 import TcType ( newTyVarTy, zonkTcType )
28 import Inst ( plusLIE )
29 import TcBinds ( tcTopBinds )
30 import TcClassDcl ( tcClassDecls2 )
31 import TcDefaults ( tcDefaults, defaultDefaultTys )
32 import TcExpr ( tcMonoExpr )
33 import TcEnv ( TcEnv, InstInfo, tcExtendGlobalValEnv,
34 isLocalThing, tcSetEnv, tcSetInstEnv, initTcEnv, getTcGEnv
36 import TcRules ( tcIfaceRules, tcSourceRules )
37 import TcForeign ( tcForeignImports, tcForeignExports )
38 import TcIfaceSig ( tcInterfaceSigs )
39 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
40 import TcSimplify ( tcSimplifyTop )
41 import TcTyClsDecls ( tcTyAndClassDecls )
43 import CoreUnfold ( unfoldingTemplate, hasUnfolding )
44 import Type ( funResultTy, splitForAllTys, openTypeKind )
45 import Bag ( isEmptyBag )
46 import ErrUtils ( printErrorsAndWarnings, dumpIfSet_dyn, showPass )
47 import Id ( idType, idUnfolding )
48 import Module ( Module )
49 import Name ( Name, toRdrName )
50 import Name ( nameEnvElts, lookupNameEnv )
51 import TyCon ( tyConGenInfo )
53 import BasicTypes ( EP(..), Fixity )
54 import Bag ( isEmptyBag )
56 import HscTypes ( PersistentCompilerState(..), HomeSymbolTable,
57 PackageTypeEnv, ModIface(..),
58 TypeEnv, extendTypeEnvList,
59 TyThing(..), implicitTyThingIds,
64 Outside-world interface:
67 -- Convenient type synonyms first:
70 -- All these fields have info *just for this module*
71 tc_env :: TypeEnv, -- The top level TypeEnv
72 tc_binds :: TypecheckedMonoBinds, -- Bindings
73 tc_fords :: [TypecheckedForeignDecl], -- Foreign import & exports.
74 tc_rules :: [TypecheckedRuleDecl] -- Transformation rules
80 -> PersistentCompilerState
82 -> ModIface -- Iface for this module
83 -> PrintUnqualified -- For error printing
85 -> IO (Maybe (PersistentCompilerState, TcResults))
86 -- The new PCS is Augmented with imported information,
87 -- (but not stuff from this module)
90 typecheckModule dflags pcs hst mod_iface unqual decls
91 = do { maybe_tc_result <- typecheck dflags pcs hst unqual $
92 tcModule pcs hst get_fixity this_mod decls
93 ; printTcDump dflags maybe_tc_result
94 ; return maybe_tc_result }
96 this_mod = mi_module mod_iface
97 fixity_env = mi_fixities mod_iface
99 get_fixity :: Name -> Maybe Fixity
100 get_fixity nm = lookupNameEnv fixity_env nm
103 typecheckExpr :: DynFlags
104 -> PersistentCompilerState
106 -> PrintUnqualified -- For error printing
108 -> (RenamedHsExpr, -- The expression itself
109 [RenamedHsDecl]) -- Plus extra decls it sucked in from interface files
110 -> IO (Maybe (PersistentCompilerState, TypecheckedHsExpr, TcType))
112 typecheckExpr dflags pcs hst unqual this_mod (expr, decls)
113 = typecheck dflags pcs hst unqual $
115 -- use the default default settings, i.e. [Integer, Double]
116 tcSetDefaultTys defaultDefaultTys $
117 tcImports pcs hst get_fixity this_mod decls `thenTc` \ (env, new_pcs, local_inst_info, deriv_binds, local_rules) ->
118 ASSERT( null local_inst_info && nullBinds deriv_binds && null local_rules )
121 newTyVarTy openTypeKind `thenTc` \ ty ->
122 tcMonoExpr expr ty `thenTc` \ (expr', lie) ->
123 tcSimplifyTop lie `thenTc` \ binds ->
124 let all_expr = mkHsLet binds expr' in
125 zonkExpr all_expr `thenNF_Tc` \ zonked_expr ->
126 zonkTcType ty `thenNF_Tc` \ zonked_ty ->
127 returnTc (new_pcs, zonked_expr, zonked_ty)
129 get_fixity :: Name -> Maybe Fixity
130 get_fixity n = pprPanic "typecheckExpr" (ppr n)
133 typecheck :: DynFlags
134 -> PersistentCompilerState
136 -> PrintUnqualified -- For error printing
140 typecheck dflags pcs hst unqual thing_inside
141 = do { showPass dflags "Typechecker";
142 ; env <- initTcEnv hst (pcs_PTE pcs)
144 ; (maybe_tc_result, (warns,errs)) <- initTc dflags env thing_inside
146 ; printErrorsAndWarnings unqual (errs,warns)
148 ; if isEmptyBag errs then
149 return maybe_tc_result
155 The internal monster:
157 tcModule :: PersistentCompilerState
159 -> (Name -> Maybe Fixity)
162 -> TcM (PersistentCompilerState, TcResults)
164 tcModule pcs hst get_fixity this_mod decls
165 = -- Type-check the type and class decls, and all imported decls
166 tcImports pcs hst get_fixity this_mod decls `thenTc` \ (env, new_pcs, local_inst_info, deriv_binds, local_rules) ->
170 -- Foreign import declarations next
171 -- traceTc (text "Tc4") `thenNF_Tc_`
172 tcForeignImports decls `thenTc` \ (fo_ids, foi_decls) ->
173 tcExtendGlobalValEnv fo_ids $
175 -- Default declarations
176 tcDefaults decls `thenTc` \ defaulting_tys ->
177 tcSetDefaultTys defaulting_tys $
179 -- Value declarations next.
180 -- We also typecheck any extra binds that came out of the "deriving" process
181 -- traceTc (text "Tc5") `thenNF_Tc_`
182 tcTopBinds (val_binds `ThenBinds` deriv_binds) `thenTc` \ ((val_binds, env), lie_valdecls) ->
185 -- Foreign export declarations next
186 -- traceTc (text "Tc6") `thenNF_Tc_`
187 tcForeignExports decls `thenTc` \ (lie_fodecls, foe_binds, foe_decls) ->
189 -- Second pass over class and instance declarations,
190 -- to compile the bindings themselves.
191 tcInstDecls2 local_inst_info `thenNF_Tc` \ (lie_instdecls, inst_binds) ->
192 tcClassDecls2 this_mod tycl_decls `thenNF_Tc` \ (lie_clasdecls, cls_dm_binds) ->
193 tcSourceRules source_rules `thenNF_Tc` \ (lie_rules, more_local_rules) ->
195 -- Deal with constant or ambiguous InstIds. How could
196 -- there be ambiguous ones? They can only arise if a
197 -- top-level decl falls under the monomorphism
198 -- restriction, and no subsequent decl instantiates its
199 -- type. (Usually, ambiguous type variables are resolved
200 -- during the generalisation step.)
202 lie_alldecls = lie_valdecls `plusLIE`
203 lie_instdecls `plusLIE`
204 lie_clasdecls `plusLIE`
205 lie_fodecls `plusLIE`
208 tcSimplifyTop lie_alldecls `thenTc` \ const_inst_binds ->
210 -- Backsubstitution. This must be done last.
211 -- Even tcSimplifyTop may do some unification.
213 all_binds = val_binds `AndMonoBinds`
214 inst_binds `AndMonoBinds`
215 cls_dm_binds `AndMonoBinds`
216 const_inst_binds `AndMonoBinds`
219 -- traceTc (text "Tc9") `thenNF_Tc_`
220 zonkTopBinds all_binds `thenNF_Tc` \ (all_binds', final_env) ->
222 -- zonkTopBinds puts all the top-level Ids into the tcGEnv
223 zonkForeignExports foe_decls `thenNF_Tc` \ foe_decls' ->
224 zonkRules more_local_rules `thenNF_Tc` \ more_local_rules' ->
227 let local_things = filter (isLocalThing this_mod) (nameEnvElts (getTcGEnv final_env))
229 -- Create any necessary "implicit" bindings (data constructors etc)
230 -- Should we create bindings for dictionary constructors?
231 -- They are always fully applied, and the bindings are just there
232 -- to support partial applications. But it's easier to let them through.
233 implicit_binds = andMonoBindList [ CoreMonoBind id (unfoldingTemplate unf)
234 | id <- implicitTyThingIds local_things
235 , let unf = idUnfolding id
239 local_type_env :: TypeEnv
240 local_type_env = mkTypeEnv local_things
242 all_local_rules = local_rules ++ more_local_rules'
244 -- traceTc (text "Tc10") `thenNF_Tc_`
246 TcResults { tc_env = local_type_env,
247 tc_binds = implicit_binds `AndMonoBinds` all_binds',
248 tc_fords = foi_decls ++ foe_decls',
249 tc_rules = all_local_rules
253 tycl_decls = [d | TyClD d <- decls]
254 val_binds = foldr ThenBinds EmptyBinds [binds | ValD binds <- decls]
255 source_rules = [d | RuleD d <- decls, not (isIfaceRuleDecl d)]
260 tcImports :: PersistentCompilerState
262 -> (Name -> Maybe Fixity)
265 -> TcM (TcEnv, PersistentCompilerState,
266 [InstInfo], RenamedHsBinds, [TypecheckedRuleDecl])
268 -- tcImports is a slight mis-nomer.
269 -- It deals with everythign that could be an import:
270 -- type and class decls
271 -- interface signatures
274 -- These can occur in source code too, of course
276 tcImports pcs hst get_fixity this_mod decls
277 = fixTc (\ ~(unf_env, _, _, _, _) ->
278 -- (unf_env :: RecTcEnv) is used for type-checking interface pragmas
279 -- which is done lazily [ie failure just drops the pragma
280 -- without having any global-failure effect].
282 -- unf_env is also used to get the pragama info
283 -- for imported dfuns and default methods
285 -- traceTc (text "Tc1") `thenNF_Tc_`
286 tcTyAndClassDecls unf_env tycl_decls `thenTc` \ env ->
289 -- Typecheck the instance decls, includes deriving
290 -- traceTc (text "Tc2") `thenNF_Tc_`
291 tcInstDecls1 (pcs_insts pcs) (pcs_PRS pcs)
292 hst unf_env get_fixity this_mod
293 decls `thenTc` \ (new_pcs_insts, inst_env, local_inst_info, deriv_binds) ->
294 tcSetInstEnv inst_env $
296 -- Interface type signatures
297 -- We tie a knot so that the Ids read out of interfaces are in scope
298 -- when we read their pragmas.
299 -- What we rely on is that pragmas are typechecked lazily; if
300 -- any type errors are found (ie there's an inconsistency)
301 -- we silently discard the pragma
302 -- traceTc (text "Tc3") `thenNF_Tc_`
303 tcInterfaceSigs unf_env tycl_decls `thenTc` \ sig_ids ->
304 tcExtendGlobalValEnv sig_ids $
307 tcIfaceRules (pcs_rules pcs) this_mod iface_rules `thenNF_Tc` \ (new_pcs_rules, local_rules) ->
309 tcGetEnv `thenTc` \ unf_env ->
311 imported_things = filter (not . isLocalThing this_mod) (nameEnvElts (getTcGEnv unf_env))
313 new_pte :: PackageTypeEnv
314 new_pte = extendTypeEnvList (pcs_PTE pcs) imported_things
316 new_pcs :: PersistentCompilerState
317 new_pcs = pcs { pcs_PTE = new_pte,
318 pcs_insts = new_pcs_insts,
319 pcs_rules = new_pcs_rules
322 returnTc (unf_env, new_pcs, local_inst_info, deriv_binds, local_rules)
325 tycl_decls = [d | TyClD d <- decls]
326 iface_rules = [d | RuleD d <- decls, isIfaceRuleDecl d]
329 %************************************************************************
331 \subsection{Dumping output}
333 %************************************************************************
336 printTcDump dflags Nothing = return ()
337 printTcDump dflags (Just (_, results))
338 = do dumpIfSet_dyn dflags Opt_D_dump_types
339 "Type signatures" (dump_sigs results)
340 dumpIfSet_dyn dflags Opt_D_dump_tc
341 "Typechecked" (dump_tc results)
344 = vcat [ppr (tc_binds results),
345 pp_rules (tc_rules results),
346 ppr_gen_tycons [tc | ATyCon tc <- nameEnvElts (tc_env results)]
349 dump_sigs results -- Print type signatures
350 = -- Convert to HsType so that we get source-language style printing
351 -- And sort by RdrName
352 vcat $ map ppr_sig $ sortLt lt_sig $
353 [ (toRdrName id, toHsType (idType id))
354 | AnId id <- nameEnvElts (tc_env results),
358 lt_sig (n1,_) (n2,_) = n1 < n2
359 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
361 want_sig id | opt_PprStyle_Debug = True
362 | otherwise = True -- For now
364 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
365 vcat (map ppr_gen_tycon tcs),
369 -- x&y are now Id's, not CoreExpr's
371 | Just ep <- tyConGenInfo tycon
372 = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
374 | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
377 = vcat [ ptext SLIT("Rep type:") <+> ppr (funResultTy from_tau),
378 ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
379 ptext SLIT("To:") <+> ppr (unfoldingTemplate (idUnfolding to))
382 (_,from_tau) = splitForAllTys (idType from)
385 pp_rules rs = vcat [ptext SLIT("{-# RULES"),
386 nest 4 (vcat (map ppr rs)),