2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
9 mkGlobalContext, getModuleContents,
11 tcRnModule, checkOldIface, importSupportingDecls,
12 tcRnIface, tcRnExtCore, tcRnStmt, tcRnExpr, tcRnThing
15 #include "HsVersions.h"
17 import CmdLineOpts ( DynFlag(..), opt_PprStyle_Debug, dopt )
18 import HsSyn ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..), HsExpr(..),
19 Stmt(..), Pat(VarPat), HsStmtContext(..), RuleDecl(..),
20 mkSimpleMatch, placeHolderType, toHsType, andMonoBinds,
21 isSrcRule, collectStmtsBinders
23 import RdrHsSyn ( RdrNameHsModule, RdrNameHsDecl, RdrNameStmt, RdrNameHsExpr )
25 import PrelNames ( iNTERACTIVE, ioTyConName, printName,
26 returnIOName, bindIOName, failIOName, thenIOName, runIOName,
27 dollarMainName, itName, mAIN_Name
29 import MkId ( unsafeCoerceId )
30 import RdrName ( RdrName, getRdrName, mkUnqual, mkRdrUnqual,
31 lookupRdrEnv, elemRdrEnv )
33 import RnHsSyn ( RenamedHsDecl, RenamedStmt, RenamedTyClDecl,
34 ruleDeclFVs, instDeclFVs, tyClDeclFVs )
35 import TcHsSyn ( TypecheckedHsExpr, TypecheckedRuleDecl,
36 zonkTopBinds, zonkTopDecls, mkHsLet,
37 zonkTopExpr, zonkTopBndrs
40 import TcExpr ( tcExpr_id )
42 import TcMType ( newTyVarTy, zonkTcType )
43 import TcType ( Type, liftedTypeKind,
44 tyVarsOfType, tcFunResultTy,
45 mkForAllTys, mkFunTys, mkTyConApp, tcSplitForAllTys
47 import TcMatches ( tcStmtsAndThen )
48 import Inst ( showLIE )
49 import TcBinds ( tcTopBinds )
50 import TcClassDcl ( tcClassDecls2 )
51 import TcDefaults ( tcDefaults )
52 import TcEnv ( RecTcGblEnv,
55 tcExtendInstEnv, tcExtendRules,
56 tcLookupTyCon, tcLookupGlobal,
59 import TcRules ( tcRules )
60 import TcForeign ( tcForeignImports, tcForeignExports )
61 import TcIfaceSig ( tcInterfaceSigs, tcCoreBinds )
62 import TcInstDcls ( tcInstDecls1, tcIfaceInstDecls, tcInstDecls2 )
63 import TcSimplify ( tcSimplifyTop, tcSimplifyInfer )
64 import TcTyClsDecls ( tcTyAndClassDecls )
66 import RnNames ( rnImports, exportsFromAvail, reportUnusedNames )
67 import RnIfaces ( slurpImpDecls, checkVersions, RecompileRequired, outOfDate )
68 import RnHiFiles ( readIface, loadOldIface )
69 import RnEnv ( lookupSrcName, lookupOccRn,
70 ubiquitousNames, implicitModuleFVs, implicitStmtFVs, dataTcOccs )
71 import RnExpr ( rnStmts, rnExpr )
72 import RnSource ( rnSrcDecls, rnExtCoreDecls, checkModDeprec, rnStats )
74 import OccName ( varName )
75 import CoreUnfold ( unfoldingTemplate )
76 import CoreSyn ( IdCoreRule, Bind(..) )
77 import PprCore ( pprIdRules, pprCoreBindings )
78 import TysWiredIn ( mkListTy, unitTy )
79 import ErrUtils ( mkDumpDoc, showPass )
80 import Id ( Id, mkLocalId, isLocalId, idName, idType, idUnfolding, setIdLocalExported )
81 import IdInfo ( GlobalIdDetails(..) )
82 import Var ( Var, setGlobalIdDetails )
83 import Module ( Module, moduleName, moduleUserString )
84 import Name ( Name, isExternalName, getSrcLoc, nameOccName )
85 import NameEnv ( delListFromNameEnv )
87 import TyCon ( tyConGenInfo )
88 import BasicTypes ( EP(..), RecFlag(..) )
89 import SrcLoc ( noSrcLoc )
91 import HscTypes ( PersistentCompilerState(..), InteractiveContext(..),
92 ModIface, ModDetails(..), ModGuts(..),
94 ModIface(..), ModDetails(..), IfaceDecls(..),
96 Deprecations(..), plusDeprecs,
98 GenAvailInfo(Avail), availsToNameSet,
100 TypeEnv, TyThing, typeEnvTyCons,
101 extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
102 extendLocalRdrEnv, emptyFixityEnv
105 import RdrName ( rdrEnvElts )
106 import RnHiFiles ( loadInterface )
107 import RnEnv ( mkGlobalRdrEnv, plusGlobalRdrEnv )
108 import HscTypes ( GlobalRdrElt(..), GlobalRdrEnv, ImportReason(..), Provenance(..),
112 import Maybe ( catMaybes )
113 import Panic ( showException )
114 import List ( partition )
115 import Util ( sortLt )
120 %************************************************************************
122 Typecheck and rename a module
124 %************************************************************************
128 tcRnModule :: HscEnv -> PersistentCompilerState
130 -> IO (PersistentCompilerState, Maybe TcGblEnv)
132 tcRnModule hsc_env pcs
133 (HsModule this_mod _ exports import_decls local_decls mod_deprec loc)
134 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
136 initTc hsc_env pcs this_mod $ addSrcLoc loc $
137 do { -- Deal with imports; sets tcg_rdr_env, tcg_imports
138 (rdr_env, imports) <- rnImports import_decls ;
139 updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
140 tcg_imports = imports })
142 traceRn (text "rn1") ;
143 -- Fail if there are any errors so far
144 -- The error printing (if needed) takes advantage
145 -- of the tcg_env we have now set
148 traceRn (text "rn1a") ;
149 -- Rename and type check the declarations
150 (tcg_env, src_fvs) <- tcRnSrcDecls local_decls ;
151 setGblEnv tcg_env $ do {
152 traceRn (text "rn2") ;
155 (tcg_env, main_fvs) <- checkMain ;
156 setGblEnv tcg_env $ do {
158 traceRn (text "rn3") ;
159 -- Check whether the entire module is deprecated
160 -- This happens only once per module
161 -- Returns the full new deprecations; a module deprecation
162 -- over-rides the earlier ones
163 let { mod_deprecs = checkModDeprec mod_deprec } ;
164 updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` mod_deprecs })
167 traceRn (text "rn4") ;
168 -- Process the export list
169 export_avails <- exportsFromAvail exports ;
170 updGblEnv (\gbl -> gbl { tcg_exports = export_avails })
173 -- Get the supporting decls for the exports
174 -- This is important *only* to gether usage information
175 -- (see comments with MkIface.mkImportInfo for why)
176 -- For OneShot compilation we could just throw away the decls
177 -- but for Batch or Interactive we must put them in the type
178 -- envt because they've been removed from the holding pen
179 let { export_fvs = availsToNameSet export_avails } ;
180 tcg_env <- importSupportingDecls export_fvs ;
181 setGblEnv tcg_env $ do {
183 -- Report unused names
184 let { used_fvs = src_fvs `plusFV` main_fvs `plusFV` export_fvs } ;
185 reportUnusedNames tcg_env used_fvs ;
187 -- Dump output and return
194 %*********************************************************
196 \subsection{Closing up the interface decls}
198 %*********************************************************
200 Suppose we discover we don't need to recompile. Then we start from the
201 IfaceDecls in the ModIface, and fluff them up by sucking in all the decls they need.
205 -> PersistentCompilerState
206 -> ModIface -- Get the decls from here
207 -> IO (PersistentCompilerState, Maybe ModDetails)
208 -- Nothing <=> errors happened
209 tcRnIface hsc_env pcs
210 (ModIface {mi_module = mod, mi_decls = iface_decls})
211 = initTc hsc_env pcs mod $ do {
213 -- Get the supporting decls, and typecheck them all together
214 -- so that any mutually recursive types are done right
215 extra_decls <- slurpImpDecls needed ;
216 env <- typecheckIfaceDecls (decls ++ extra_decls) ;
218 returnM (ModDetails { md_types = tcg_type_env env,
219 md_insts = tcg_insts env,
220 md_rules = hsCoreRules (tcg_rules env)
221 -- All the rules from an interface are of the IfaceRuleOut form
224 rule_decls = dcl_rules iface_decls
225 inst_decls = dcl_insts iface_decls
226 tycl_decls = dcl_tycl iface_decls
227 decls = map RuleD rule_decls ++
228 map InstD inst_decls ++
230 needed = unionManyNameSets (map ruleDeclFVs rule_decls) `unionNameSets`
231 unionManyNameSets (map instDeclFVs inst_decls) `unionNameSets`
232 unionManyNameSets (map tyClDeclFVs tycl_decls) `unionNameSets`
234 -- Data type decls with record selectors,
235 -- which may appear in the decls, need unpackCString
236 -- and friends. It's easier to just grab them right now.
238 hsCoreRules :: [TypecheckedRuleDecl] -> [IdCoreRule]
239 -- All post-typechecking Iface rules have the form IfaceRuleOut
240 hsCoreRules rules = [(id,rule) | IfaceRuleOut id rule <- rules]
244 %************************************************************************
246 The interactive interface
248 %************************************************************************
251 tcRnStmt :: HscEnv -> PersistentCompilerState
252 -> InteractiveContext
254 -> IO (PersistentCompilerState,
255 Maybe (InteractiveContext, [Name], TypecheckedHsExpr))
256 -- The returned [Id] is the same as the input except for
257 -- ExprStmt, in which case the returned [Name] is [itName]
259 tcRnStmt hsc_env pcs ictxt rdr_stmt
260 = initTc hsc_env pcs iNTERACTIVE $
261 setInteractiveContext ictxt $ do {
263 -- Rename; use CmdLineMode because tcRnStmt is only used interactively
264 ([rn_stmt], fvs) <- initRnInteractive ictxt
265 (rnStmts DoExpr [rdr_stmt]) ;
266 traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
269 -- Suck in the supporting declarations and typecheck them
270 tcg_env <- importSupportingDecls (fvs `plusFV` implicitStmtFVs fvs) ;
271 -- NB: an earlier version deleted (rdrEnvElts local_env) from
272 -- the fvs. But (a) that isn't necessary, because previously
273 -- bound things in the local_env will be in the TypeEnv, and
274 -- the renamer doesn't re-slurp such things, and
275 -- (b) it's WRONG to delete them. Consider in GHCi:
276 -- Mod> let x = e :: T
277 -- Mod> let y = x + 3
278 -- We need to pass 'x' among the fvs to slurpImpDecls, so that
279 -- the latter can see that T is a gate, and hence import the Num T
280 -- instance decl. (See the InTypEnv case in RnIfaces.slurpSourceRefs.)
281 setGblEnv tcg_env $ do {
283 -- The real work is done here
284 ((bound_ids, tc_expr), lie) <- getLIE (tcUserStmt rn_stmt) ;
286 traceTc (text "tcs 1") ;
287 let { -- Make all the bound ids "global" ids, now that
288 -- they're notionally top-level bindings. This is
289 -- important: otherwise when we come to compile an expression
290 -- using these ids later, the byte code generator will consider
291 -- the occurrences to be free rather than global.
292 global_ids = map globaliseId bound_ids ;
293 globaliseId id = setGlobalIdDetails id VanillaGlobal ;
295 -- Update the interactive context
296 rn_env = ic_rn_local_env ictxt ;
297 type_env = ic_type_env ictxt ;
299 bound_names = map idName global_ids ;
300 new_rn_env = extendLocalRdrEnv rn_env bound_names ;
302 -- Remove any shadowed bindings from the type_env;
303 -- they are inaccessible but might, I suppose, cause
304 -- a space leak if we leave them there
305 shadowed = [ n | name <- bound_names,
306 let rdr_name = mkRdrUnqual (nameOccName name),
307 Just n <- [lookupRdrEnv rn_env rdr_name] ] ;
309 filtered_type_env = delListFromNameEnv type_env shadowed ;
310 new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;
312 new_ic = ictxt { ic_rn_local_env = new_rn_env,
313 ic_type_env = new_type_env }
316 dumpOptTcRn Opt_D_dump_tc
317 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
318 text "Typechecked expr" <+> ppr tc_expr]) ;
320 returnM (new_ic, bound_names, tc_expr)
325 Here is the grand plan, implemented in tcUserStmt
327 What you type The IO [HValue] that hscStmt returns
328 ------------- ------------------------------------
329 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
332 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
335 expr (of IO type) ==> expr >>= \ v -> return [coerce HVal v]
336 [NB: result not printed] bindings: [it]
338 expr (of non-IO type, ==> let v = expr in print v >> return [coerce HVal v]
339 result showable) bindings: [it]
341 expr (of non-IO type,
342 result not showable) ==> error
346 ---------------------------
347 tcUserStmt :: RenamedStmt -> TcM ([Id], TypecheckedHsExpr)
348 tcUserStmt (ExprStmt expr _ loc)
349 = newUnique `thenM` \ uniq ->
351 fresh_it = itName uniq
352 the_bind = FunMonoBind fresh_it False
353 [ mkSimpleMatch [] expr placeHolderType loc ] loc
355 tryTc_ (do { -- Try this if the other fails
356 traceTc (text "tcs 1b") ;
358 LetStmt (MonoBind the_bind [] NonRecursive),
359 ExprStmt (HsApp (HsVar printName) (HsVar fresh_it))
360 placeHolderType loc] })
361 (do { -- Try this first
362 traceTc (text "tcs 1a") ;
363 tc_stmts [BindStmt (VarPat fresh_it) expr loc] })
365 tcUserStmt stmt = tc_stmts [stmt]
367 ---------------------------
369 = do { io_ids <- mappM tcLookupId
370 [returnIOName, failIOName, bindIOName, thenIOName] ;
371 ioTyCon <- tcLookupTyCon ioTyConName ;
372 res_ty <- newTyVarTy liftedTypeKind ;
374 names = collectStmtsBinders stmts ;
375 return_id = head io_ids ; -- Rather gruesome
377 io_ty = (\ ty -> mkTyConApp ioTyCon [ty], res_ty) ;
379 -- mk_return builds the expression
380 -- returnIO @ [()] [coerce () x, .., coerce () z]
381 mk_return ids = HsApp (TyApp (HsVar return_id) [mkListTy unitTy])
382 (ExplicitList unitTy (map mk_item ids)) ;
384 mk_item id = HsApp (TyApp (HsVar unsafeCoerceId) [idType id, unitTy])
387 -- OK, we're ready to typecheck the stmts
388 traceTc (text "tcs 2") ;
389 ((ids, tc_stmts), lie) <-
390 getLIE $ tcStmtsAndThen combine DoExpr io_ty stmts $
392 -- Look up the names right in the middle,
393 -- where they will all be in scope
394 ids <- mappM tcLookupId names ;
395 return (ids, [ResultStmt (mk_return ids) noSrcLoc])
398 -- Simplify the context right here, so that we fail
399 -- if there aren't enough instances. Notably, when we see
401 -- we use tryTc_ to try it <- e
402 -- and then let it = e
403 -- It's the simplify step that rejects the first.
404 traceTc (text "tcs 3") ;
405 const_binds <- tcSimplifyTop lie ;
407 -- Build result expression and zonk it
408 let { expr = mkHsLet const_binds $
409 HsDo DoExpr tc_stmts io_ids
410 (mkTyConApp ioTyCon [mkListTy unitTy]) noSrcLoc } ;
411 zonked_expr <- zonkTopExpr expr ;
412 zonked_ids <- zonkTopBndrs ids ;
414 return (zonked_ids, zonked_expr)
417 combine stmt (ids, stmts) = (ids, stmt:stmts)
421 tcRnExpr just finds the type of an expression
424 tcRnExpr :: HscEnv -> PersistentCompilerState
425 -> InteractiveContext
427 -> IO (PersistentCompilerState, Maybe Type)
428 tcRnExpr hsc_env pcs ictxt rdr_expr
429 = initTc hsc_env pcs iNTERACTIVE $
430 setInteractiveContext ictxt $ do {
432 (rn_expr, fvs) <- initRnInteractive ictxt (rnExpr rdr_expr) ;
435 -- Suck in the supporting declarations and typecheck them
436 tcg_env <- importSupportingDecls (fvs `plusFV` ubiquitousNames) ;
437 setGblEnv tcg_env $ do {
439 -- Now typecheck the expression;
440 -- it might have a rank-2 type (e.g. :t runST)
441 -- Hence the hole type (c.f. TcExpr.tcExpr_id)
442 ((tc_expr, res_ty), lie) <- getLIE (tcExpr_id rn_expr) ;
443 ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie) ;
444 tcSimplifyTop lie_top ;
446 let { all_expr_ty = mkForAllTys qtvs $
447 mkFunTys (map idType dict_ids) $
449 zonkTcType all_expr_ty
452 smpl_doc = ptext SLIT("main expression")
457 tcRnThing :: HscEnv -> PersistentCompilerState
458 -> InteractiveContext
460 -> IO (PersistentCompilerState, Maybe [TyThing])
461 -- Look up a RdrName and return all the TyThings it might be
462 -- We treat a capitalised RdrName as both a data constructor
463 -- and as a type or class constructor; hence we return up to two results
464 tcRnThing hsc_env pcs ictxt rdr_name
465 = initTc hsc_env pcs iNTERACTIVE $
466 setInteractiveContext ictxt $ do {
468 -- If the identifier is a constructor (begins with an
469 -- upper-case letter), then we need to consider both
470 -- constructor and type class identifiers.
471 let { rdr_names = dataTcOccs rdr_name } ;
473 (msgs_s, mb_names) <- initRnInteractive ictxt
474 (mapAndUnzipM (tryM . lookupOccRn) rdr_names) ;
475 let { names = catMaybes mb_names } ;
478 do { addMessages (head msgs_s) ; failM }
481 mapM_ addMessages msgs_s ; -- Add deprecation warnings
482 mapM tcLookupGlobal names -- and lookup up the entities
488 setInteractiveContext :: InteractiveContext -> TcRn m a -> TcRn m a
489 setInteractiveContext icxt thing_inside
490 = traceTc (text "setIC" <+> ppr (ic_type_env icxt)) `thenM_`
491 updGblEnv (\ env -> env { tcg_rdr_env = ic_rn_gbl_env icxt,
492 tcg_type_env = ic_type_env icxt })
495 initRnInteractive :: InteractiveContext -> RnM a -> TcM a
496 -- Set the local RdrEnv from the interactive context
497 initRnInteractive ictxt rn_thing
498 = initRn CmdLineMode $
499 setLocalRdrEnv (ic_rn_local_env ictxt) $
503 %************************************************************************
505 Type-checking external-core modules
507 %************************************************************************
510 tcRnExtCore :: HscEnv -> PersistentCompilerState
512 -> IO (PersistentCompilerState, Maybe ModGuts)
513 -- Nothing => some error occurred
515 tcRnExtCore hsc_env pcs
516 (HsModule this_mod _ _ _ local_decls _ loc)
517 -- Rename the (Core) module. It's a bit like an interface
518 -- file: all names are original names
519 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
521 initTc hsc_env pcs this_mod $ addSrcLoc loc $ do {
523 -- Rename the source, only in interface mode.
524 -- rnSrcDecls handles fixity decls etc too, which won't occur
525 -- but that doesn't matter
526 (rn_local_decls, fvs) <- initRn (InterfaceMode this_mod)
527 (rnExtCoreDecls local_decls) ;
530 -- Get the supporting decls, and typecheck them all together
531 -- so that any mutually recursive types are done right
532 extra_decls <- slurpImpDecls fvs ;
533 tcg_env <- typecheckIfaceDecls (rn_local_decls ++ extra_decls) ;
534 setGblEnv tcg_env $ do {
536 -- Now the core bindings
537 core_prs <- tcCoreBinds [d | CoreD d <- rn_local_decls] ;
538 tcExtendGlobalValEnv (map fst core_prs) $ do {
542 bndrs = map fst core_prs ;
543 my_exports = map (Avail . idName) bndrs ;
544 -- ToDo: export the data types also?
546 final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
548 mod_guts = ModGuts { mg_module = this_mod,
549 mg_usages = [], -- ToDo: compute usage
550 mg_dir_imps = [], -- ??
551 mg_exports = my_exports,
552 mg_types = final_type_env,
553 mg_insts = tcg_insts tcg_env,
554 mg_rules = hsCoreRules (tcg_rules tcg_env),
555 mg_binds = [Rec core_prs],
558 mg_rdr_env = emptyGlobalRdrEnv,
559 mg_fix_env = emptyFixityEnv,
560 mg_deprecs = NoDeprecs,
564 tcCoreDump mod_guts ;
571 %************************************************************************
573 Type-checking the top level of a module
575 %************************************************************************
577 tcRnSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, FreeVars)
578 -- Returns the variables free in the decls
579 tcRnSrcDecls [] = getGblEnv
581 = do { let { (first_group, group_tail) = findSplice ds } ;
583 tcg_env <- tcRnGroup first_group ;
586 Nothing -> return gbl_env
587 Just (splice_expr, rest_ds) -> do {
589 setGblEnv tcg_env $ do {
591 -- Rename the splice expression, and get its supporting decls
592 (rn_splice_expr, fvs) <- initRn SourceMode (rnExpr splice_expr) ;
593 tcg_env <- importSupportingDecls fvs ;
594 setGblEnv tcg_env $ do {
596 -- Execute the splice
597 spliced_decls <- tcSpliceDecls rn_splice_expr ;
599 -- Glue them on the front of the remaining decls and loop
600 tcRnSrcDeclsDecls (splice_decls ++ rest_ds)
603 findSplice :: [HsDecl a] -> ([HsDecl a], Maybe (HsExpr a, [HsDecl a]))
604 findSplice [] = ([], Nothing)
605 findSplice (SpliceD e : ds) = ([], Just (e, ds))
606 findSplice (d : ds) = (d:gs, rest)
608 (gs, rest) = findSplice ds
611 %************************************************************************
613 Type-checking the top level of a module
615 %************************************************************************
617 tcRnSrcDecls takes a bunch of top-level source-code declarations, and
619 * gets supporting declarations from interface files
622 * and augments the TcGblEnv with the results
624 In Template Haskell it may be called repeatedly for each group of
625 declarations. It expects there to be an incoming TcGblEnv in the
626 monad; it augments it and returns the new TcGblEnv.
629 tcRnSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, FreeVars)
630 -- Returns the variables free in the decls
632 = do { -- Rename the declarations
633 (tcg_env, rn_decls, src_fvs) <- rnTopSrcDecls decls ;
634 setGblEnv tcg_env $ do {
636 -- Typecheck the declarations
637 tcg_env <- tcTopSrcDecls rn_decls ;
638 return (tcg_env, src_fvs)
641 ------------------------------------------------
642 rnTopSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, [RenamedHsDecl], FreeVars)
644 = do { (tcg_env, rn_src_decls, src_fvs) <- initRn SourceMode (rnSrcDecls decls) ;
645 setGblEnv tcg_env $ do {
649 -- Import consquential imports
650 rn_imp_decls <- slurpImpDecls (src_fvs `plusFV` implicitModuleFVs src_fvs) ;
651 let { rn_decls = rn_src_decls ++ rn_imp_decls } ;
653 -- Dump trace of renaming part
654 rnDump (vcat (map ppr rn_decls)) ;
655 rnStats rn_imp_decls ;
657 return (tcg_env, rn_decls, src_fvs)
660 ------------------------------------------------
661 tcTopSrcDecls :: [RenamedHsDecl] -> TcM TcGblEnv
662 tcTopSrcDecls rn_decls
663 = fixM (\ unf_env -> do {
664 -- Loop back the final environment, including the fully zonked
665 -- versions of bindings from this module. In the presence of mutual
666 -- recursion, interface type signatures may mention variables defined
667 -- in this module, which is why the knot is so big
670 ((tcg_env, binds, rules, fords), lie) <- getLIE (
671 tc_src_decls unf_env rn_decls
674 -- tcSimplifyTop deals with constant or ambiguous InstIds.
675 -- How could there be ambiguous ones? They can only arise if a
676 -- top-level decl falls under the monomorphism
677 -- restriction, and no subsequent decl instantiates its
678 -- type. (Usually, ambiguous type variables are resolved
679 -- during the generalisation step.)
680 traceTc (text "Tc8") ;
681 inst_binds <- setGblEnv tcg_env (tcSimplifyTop lie) ;
682 -- The setGblEnv exposes the instances to tcSimplifyTop
684 -- Backsubstitution. This must be done last.
685 -- Even tcSimplifyTop may do some unification.
686 traceTc (text "Tc9") ;
687 (ids, binds', fords', rules') <- zonkTopDecls (binds `andMonoBinds` inst_binds)
690 let { tcg_env' = tcg_env { tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) ids,
691 tcg_binds = tcg_binds tcg_env `andMonoBinds` binds',
692 tcg_rules = tcg_rules tcg_env ++ rules',
693 tcg_fords = tcg_fords tcg_env ++ fords' } } ;
698 tc_src_decls unf_env decls
699 = do { -- Type-check the type and class decls, and all imported decls
700 traceTc (text "Tc2") ;
701 tcg_env <- tcTyClDecls unf_env tycl_decls ;
702 setGblEnv tcg_env $ do {
704 -- Source-language instances, including derivings,
705 -- and import the supporting declarations
706 traceTc (text "Tc3") ;
707 (tcg_env, inst_infos, deriv_binds, fvs) <- tcInstDecls1 tycl_decls inst_decls ;
708 setGblEnv tcg_env $ do {
709 tcg_env <- importSupportingDecls fvs ;
710 setGblEnv tcg_env $ do {
712 -- Foreign import declarations next. No zonking necessary
713 -- here; we can tuck them straight into the global environment.
714 traceTc (text "Tc4") ;
715 (fi_ids, fi_decls) <- tcForeignImports decls ;
716 tcExtendGlobalValEnv fi_ids $
717 updGblEnv (\gbl -> gbl { tcg_fords = tcg_fords gbl ++ fi_decls })
720 -- Default declarations
721 traceTc (text "Tc4a") ;
722 default_tys <- tcDefaults decls ;
723 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
725 -- Value declarations next
726 -- We also typecheck any extra binds that came out
727 -- of the "deriving" process
728 traceTc (text "Tc5") ;
729 (tc_val_binds, lcl_env) <- tcTopBinds (val_binds `ThenBinds` deriv_binds) ;
730 setLclTypeEnv lcl_env $ do {
732 -- Second pass over class and instance declarations,
733 -- plus rules and foreign exports, to generate bindings
734 traceTc (text "Tc6") ;
735 (cls_dm_binds, dm_ids) <- tcClassDecls2 tycl_decls ;
736 tcExtendGlobalValEnv dm_ids $ do {
737 inst_binds <- tcInstDecls2 inst_infos ;
738 showLIE "after instDecls2" ;
741 -- They need to be zonked, so we return them
742 traceTc (text "Tc7") ;
743 (foe_binds, foe_decls) <- tcForeignExports decls ;
746 -- Need to partition them because the source rules
747 -- must be zonked before adding them to tcg_rules
748 -- NB: built-in rules come in as IfaceRuleOut's, and
749 -- get added to tcg_rules right here by tcExtendRules
750 rules <- tcRules rule_decls ;
751 let { (src_rules, iface_rules) = partition isSrcRule rules } ;
752 tcExtendRules iface_rules $ do {
755 tcg_env <- getGblEnv ;
756 let { all_binds = tc_val_binds `AndMonoBinds`
757 inst_binds `AndMonoBinds`
758 cls_dm_binds `AndMonoBinds`
761 return (tcg_env, all_binds, src_rules, foe_decls)
764 tycl_decls = [d | TyClD d <- decls]
765 rule_decls = [d | RuleD d <- decls]
766 inst_decls = [d | InstD d <- decls]
767 val_decls = [d | ValD d <- decls]
768 val_binds = foldr ThenBinds EmptyBinds val_decls
772 tcTyClDecls :: RecTcGblEnv
776 -- tcTyClDecls deals with
777 -- type and class decls (some source, some imported)
778 -- interface signatures (checked lazily)
780 -- It returns the TcGblEnv for this module, and side-effects the
781 -- persistent compiler state to reflect the things imported from
784 tcTyClDecls unf_env tycl_decls
785 -- (unf_env :: RecTcGblEnv) is used for type-checking interface pragmas
786 -- which is done lazily [ie failure just drops the pragma
787 -- without having any global-failure effect].
790 -- tcTyAndClassDecls recovers internally, but if anything gave rise to
791 -- an error we'd better stop now, to avoid a cascade
793 traceTc (text "TyCl1") `thenM_`
794 tcTyAndClassDecls tycl_decls `thenM` \ tycl_things ->
795 tcExtendGlobalEnv tycl_things $
797 -- Interface type signatures
798 -- We tie a knot so that the Ids read out of interfaces are in scope
799 -- when we read their pragmas.
800 -- What we rely on is that pragmas are typechecked lazily; if
801 -- any type errors are found (ie there's an inconsistency)
802 -- we silently discard the pragma
803 traceTc (text "TyCl2") `thenM_`
804 tcInterfaceSigs unf_env tycl_decls `thenM` \ sig_ids ->
805 tcExtendGlobalValEnv sig_ids $
807 getGblEnv -- Return the TcLocals environment
812 %************************************************************************
814 Load the old interface file for this module (unless
815 we have it aleady), and check whether it is up to date
818 %************************************************************************
821 checkOldIface :: HscEnv
822 -> PersistentCompilerState
824 -> FilePath -- Where the interface file is
825 -> Bool -- Source unchanged
826 -> Maybe ModIface -- Old interface from compilation manager, if any
827 -> IO (PersistentCompilerState, Maybe (RecompileRequired, Maybe ModIface))
828 -- Nothing <=> errors happened
830 checkOldIface hsc_env pcs mod iface_path source_unchanged maybe_iface
831 = do { showPass (hsc_dflags hsc_env)
832 ("Checking old interface for " ++ moduleUserString mod) ;
834 initTc hsc_env pcs mod
835 (check_old_iface iface_path source_unchanged maybe_iface)
838 check_old_iface iface_path source_unchanged maybe_iface
839 = -- CHECK WHETHER THE SOURCE HAS CHANGED
840 ifM (not source_unchanged)
841 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
844 -- If the source has changed and we're in interactive mode, avoid reading
845 -- an interface; just return the one we might have been supplied with.
846 getGhciMode `thenM` \ ghci_mode ->
847 if (ghci_mode == Interactive) && not source_unchanged then
848 returnM (outOfDate, maybe_iface)
852 Just old_iface -> -- Use the one we already have
853 checkVersions source_unchanged old_iface `thenM` \ recomp ->
854 returnM (recomp, Just old_iface)
856 Nothing -- Try and read it from a file
857 -> getModule `thenM` \ this_mod ->
858 readIface this_mod iface_path False `thenM` \ read_result ->
860 Left err -> -- Old interface file not found, or garbled; give up
862 text "Cannot read old interface file:"
863 $$ nest 4 (text (showException err))) `thenM_`
864 returnM (outOfDate, Nothing)
866 Right parsed_iface ->
867 initRn (InterfaceMode this_mod)
868 (loadOldIface parsed_iface) `thenM` \ m_iface ->
869 checkVersions source_unchanged m_iface `thenM` \ recomp ->
870 returnM (recomp, Just m_iface)
874 %************************************************************************
876 Type-check and rename supporting declarations
877 This is used to deal with the free vars of a splice,
878 or derived code: slurp in the necessary declarations,
879 typecheck them, and add them to the EPS
881 %************************************************************************
884 importSupportingDecls :: FreeVars -> TcM TcGblEnv
885 -- Completely deal with the supporting imports needed
886 -- by the specified free-var set
887 importSupportingDecls fvs
888 = do { traceRn (text "Import supporting decls for" <+> ppr (nameSetToList fvs)) ;
889 decls <- slurpImpDecls fvs ;
890 traceRn (text "...namely:" <+> vcat (map ppr decls)) ;
891 typecheckIfaceDecls decls }
893 typecheckIfaceDecls :: [RenamedHsDecl] -> TcM TcGblEnv
894 -- The decls are all interface-file declarations
895 -- Usually they are all from other modules, but when we are reading
896 -- this module's interface from a file, it's possible that some of
897 -- them are for the module being compiled.
898 -- That is why the tcExtendX functions need to do partitioning.
900 -- If all the decls are from other modules, the returned TcGblEnv
901 -- will have an empty tc_genv, but its tc_inst_env and tc_ist
902 -- caches may have been augmented.
903 typecheckIfaceDecls decls
904 = do { let { tycl_decls = [d | TyClD d <- decls] ;
905 inst_decls = [d | InstD d <- decls] ;
906 rule_decls = [d | RuleD d <- decls] } ;
908 -- Typecheck the type, class, and interface-sig decls
909 tcg_env <- fixM (\ unf_env -> tcTyClDecls unf_env tycl_decls) ;
910 setGblEnv tcg_env $ do {
912 -- Typecheck the instance decls, and rules
913 -- Note that imported dictionary functions are already
914 -- in scope from the preceding tcTyClDecls
915 tcIfaceInstDecls inst_decls `thenM` \ dfuns ->
916 tcExtendInstEnv dfuns $
917 tcRules rule_decls `thenM` \ rules ->
918 tcExtendRules rules $
920 getGblEnv -- Return the environment
926 %*********************************************************
928 mkGlobalContext: make up an interactive context
930 Used for initialising the lexical environment
931 of the interactive read-eval-print loop
933 %*********************************************************
938 :: HscEnv -> PersistentCompilerState
939 -> [Module] -- Expose these modules' top-level scope
940 -> [Module] -- Expose these modules' exports only
941 -> IO (PersistentCompilerState, Maybe GlobalRdrEnv)
943 mkGlobalContext hsc_env pcs toplevs exports
944 = initTc hsc_env pcs iNTERACTIVE $ do {
946 toplev_envs <- mappM getTopLevScope toplevs ;
947 export_envs <- mappM getModuleExports exports ;
948 returnM (foldr plusGlobalRdrEnv emptyGlobalRdrEnv
949 (toplev_envs ++ export_envs))
952 getTopLevScope :: Module -> TcRn m GlobalRdrEnv
954 = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
955 case mi_globals iface of
956 Nothing -> panic "getTopLevScope"
957 Just env -> returnM env }
959 getModuleExports :: Module -> TcRn m GlobalRdrEnv
961 = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
962 returnM (foldl add emptyGlobalRdrEnv (mi_exports iface)) }
964 prov_fn n = NonLocalDef ImplicitImport
966 = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True prov_fn avails NoDeprecs)
968 contextDoc = text "context for compiling statements"
974 -> PersistentCompilerState -- IN: persistent compiler state
975 -> Module -- module to inspect
976 -> Bool -- grab just the exports, or the whole toplev
977 -> IO (PersistentCompilerState, Maybe [TyThing])
979 getModuleContents hsc_env pcs mod exports_only
980 = initTc hsc_env pcs iNTERACTIVE $ do {
982 -- Load the interface if necessary (a home module will certainly
983 -- alraedy be loaded, but a package module might not be)
984 iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
986 let { export_names = availsToNameSet export_avails ;
987 export_avails = [ avail | (mn, avails) <- mi_exports iface,
988 avail <- avails ] } ;
990 all_names <- if exports_only then
992 else case mi_globals iface of {
994 return (get_locals rdr_env) ;
996 Nothing -> do { addErr (noRdrEnvErr mod) ;
997 return export_names } } ;
998 -- Invariant; we only have (not exports_only)
999 -- for a home module so it must already be in the HIT
1000 -- So the Nothing case is a bug
1002 env <- importSupportingDecls all_names ;
1003 setGblEnv env (mappM tcLookupGlobal (nameSetToList all_names))
1006 -- Grab all the things from the global env that are locally def'd
1007 get_locals rdr_env = mkNameSet [ gre_name gre
1008 | elts <- rdrEnvElts rdr_env,
1011 -- Make a set because a name is often in the envt in
1012 -- both qualified and unqualified forms
1014 noRdrEnvErr mod = ptext SLIT("No top-level environment available for module")
1015 <+> quotes (ppr mod)
1019 %************************************************************************
1023 %************************************************************************
1027 = do { ghci_mode <- getGhciMode ;
1028 tcg_env <- getGblEnv ;
1029 check_main ghci_mode tcg_env
1032 check_main ghci_mode tcg_env
1033 -- If we are in module Main, check that 'main' is defined.
1034 -- It may be imported from another module, in which case
1035 -- we have to drag in its.
1037 -- Also form the definition
1038 -- $main = runIO main
1039 -- so we need to slurp in runIO too.
1041 -- ToDo: We have to return the main_name separately, because it's a
1042 -- bona fide 'use', and should be recorded as such, but the others
1045 -- Blimey: a whole page of code to do this...
1047 | mod_name /= mAIN_Name
1048 = return (tcg_env, emptyFVs)
1050 | not (main_RDR_Unqual `elemRdrEnv` rdr_env)
1051 = do { complain_no_main; return (tcg_env, emptyFVs) }
1054 = do { -- Check that 'main' is in scope
1055 -- It might be imported from another module!
1056 main_name <- lookupSrcName main_RDR_Unqual ;
1059 tcg_env <- importSupportingDecls (unitFV runIOName) ;
1060 setGblEnv tcg_env $ do {
1062 -- $main :: IO () = runIO main
1063 let { rhs = HsApp (HsVar runIOName) (HsVar main_name) } ;
1065 (main_bind, top_lie) <- getLIE (
1066 addSrcLoc (getSrcLoc main_name) $
1067 addErrCtxt mainCtxt $ do {
1068 (main_expr, ty) <- tcExpr_id rhs ;
1069 let { dollar_main_id = setIdLocalExported (mkLocalId dollarMainName ty) } ;
1070 return (VarMonoBind dollar_main_id main_expr)
1073 inst_binds <- tcSimplifyTop top_lie ;
1075 (ids, binds') <- zonkTopBinds (main_bind `andMonoBinds` inst_binds) ;
1077 let { tcg_env' = tcg_env {
1078 tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) ids,
1079 tcg_binds = tcg_binds tcg_env `andMonoBinds` binds' } } ;
1081 return (tcg_env', unitFV main_name)
1084 mod_name = moduleName (tcg_mod tcg_env)
1085 rdr_env = tcg_rdr_env tcg_env
1087 main_RDR_Unqual :: RdrName
1088 main_RDR_Unqual = mkUnqual varName FSLIT("main")
1089 -- Don't get a RdrName from PrelNames.mainName, because
1090 -- nameRdrNamegets an Orig RdrName, and we want a Qual or Unqual one.
1091 -- An Unqual one will do just fine
1093 complain_no_main | ghci_mode == Interactive = return ()
1094 | otherwise = addErr noMainMsg
1095 -- In interactive mode, don't worry about the absence of 'main'
1097 mainCtxt = ptext SLIT("When checking the type of 'main'")
1098 noMainMsg = ptext SLIT("No 'main' defined in module Main")
1102 %************************************************************************
1106 %************************************************************************
1109 rnDump :: SDoc -> TcRn m ()
1110 -- Dump, with a banner, if -ddump-rn
1111 rnDump doc = dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc)
1113 tcDump :: TcGblEnv -> TcRn m ()
1115 = do { dflags <- getDOpts ;
1117 -- Dump short output if -ddump-types or -ddump-tc
1118 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1119 (dumpTcRn short_dump) ;
1121 -- Dump bindings if -ddump-tc
1122 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1125 short_dump = pprTcGblEnv env
1126 full_dump = ppr (tcg_binds env)
1127 -- NB: foreign x-d's have undefined's in their types;
1128 -- hence can't show the tc_fords
1131 = do { dflags <- getDOpts ;
1132 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1133 (dumpTcRn (pprModGuts mod_guts)) ;
1135 -- Dump bindings if -ddump-tc
1136 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1138 full_dump = pprCoreBindings (mg_binds mod_guts)
1140 -- It's unpleasant having both pprModGuts and pprModDetails here
1141 pprTcGblEnv :: TcGblEnv -> SDoc
1142 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
1143 tcg_insts = dfun_ids,
1144 tcg_rules = rules })
1145 = vcat [ ppr_types dfun_ids type_env
1146 , ppr_insts dfun_ids
1147 , vcat (map ppr rules)
1148 , ppr_gen_tycons (typeEnvTyCons type_env)]
1150 pprModGuts :: ModGuts -> SDoc
1151 pprModGuts (ModGuts { mg_types = type_env,
1153 = vcat [ ppr_types [] type_env,
1157 ppr_types :: [Var] -> TypeEnv -> SDoc
1158 ppr_types dfun_ids type_env
1159 = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1161 ids = [id | id <- typeEnvIds type_env, want_sig id]
1162 want_sig id | opt_PprStyle_Debug = True
1163 | otherwise = isLocalId id &&
1164 isExternalName (idName id) &&
1165 not (id `elem` dfun_ids)
1166 -- isLocalId ignores data constructors, records selectors etc.
1167 -- The isExternalName ignores local dictionary and method bindings
1168 -- that the type checker has invented. Top-level user-defined things
1169 -- have External names.
1171 ppr_insts :: [Var] -> SDoc
1172 ppr_insts [] = empty
1173 ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)
1175 ppr_sigs :: [Var] -> SDoc
1177 -- Print type signatures
1178 -- Convert to HsType so that we get source-language style printing
1179 -- And sort by RdrName
1180 = vcat $ map ppr_sig $ sortLt lt_sig $
1181 [ (getRdrName id, toHsType (idType id))
1184 lt_sig (n1,_) (n2,_) = n1 < n2
1185 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
1188 ppr_rules :: [IdCoreRule] -> SDoc
1189 ppr_rules [] = empty
1190 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1191 nest 4 (pprIdRules rs),
1194 ppr_gen_tycons [] = empty
1195 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
1196 vcat (map ppr_gen_tycon tcs),
1200 -- x&y are now Id's, not CoreExpr's
1202 | Just ep <- tyConGenInfo tycon
1203 = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
1205 | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
1208 = vcat [ ptext SLIT("Rep type:") <+> ppr (tcFunResultTy from_tau),
1209 ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
1210 ptext SLIT("To:") <+> ppr (unfoldingTemplate (idUnfolding to))
1213 (_,from_tau) = tcSplitForAllTys (idType from)