2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
9 tcRnStmt, tcRnExpr, tcRnType,
20 #include "HsVersions.h"
24 import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
27 import DynFlags ( DynFlag(..), DynFlags(..), dopt, GhcMode(..) )
28 import StaticFlags ( opt_PprStyle_Debug )
29 import HsSyn ( HsModule(..), HsExtCore(..), HsGroup(..), LHsDecl,
30 SpliceDecl(..), HsBind(..), LHsBinds,
31 emptyRdrGroup, emptyRnGroup, appendGroups, plusHsValBinds,
32 nlHsApp, nlHsVar, pprLHsBinds, HaddockModInfo(..) )
33 import RdrHsSyn ( findSplice )
35 import PrelNames ( runMainIOName, rootMainKey, rOOT_MAIN, mAIN,
37 import RdrName ( RdrName, mkRdrUnqual, emptyGlobalRdrEnv )
38 import TcHsSyn ( zonkTopDecls )
39 import TcExpr ( tcInferRho )
41 import TcType ( tidyTopType, tcEqType )
42 import Inst ( showLIE )
43 import InstEnv ( extendInstEnvList, Instance, pprInstances,
45 import FamInstEnv ( FamInst, pprFamInsts )
46 import TcBinds ( tcTopBinds, tcHsBootSigs )
47 import TcDefaults ( tcDefaults )
48 import TcEnv ( tcExtendGlobalValEnv, iDFunId )
49 import TcRules ( tcRules )
50 import TcForeign ( tcForeignImports, tcForeignExports )
51 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
52 import TcIface ( tcExtCoreBindings, tcHiBootIface )
53 import MkIface ( tyThingToIfaceDecl )
54 import IfaceSyn ( checkBootDecl, IfaceExtName(..) )
55 import TcSimplify ( tcSimplifyTop )
56 import TcTyClsDecls ( tcTyAndClassDecls )
57 import LoadIface ( loadOrphanModules )
58 import RnNames ( importsFromLocalDecls, rnImports, rnExports,
59 mkRdrEnvAndImports, mkExportNameSet,
60 reportUnusedNames, reportDeprecations )
61 import RnEnv ( lookupSrcOcc_maybe )
62 import RnSource ( rnSrcDecls, rnTyClDecls, checkModDeprec )
63 import RnHsDoc ( rnMbHsDoc )
64 import PprCore ( pprRules, pprCoreBindings )
65 import CoreSyn ( CoreRule, bindersOfBinds )
66 import ErrUtils ( Messages, mkDumpDoc, showPass )
67 import Id ( Id, mkExportedLocalId, isLocalId, idName, idType )
70 import UniqFM ( elemUFM, eltsUFM )
71 import OccName ( mkVarOccFS, plusOccEnv )
72 import Name ( Name, NamedThing(..), isExternalName, getSrcLoc, isWiredInName,
73 nameModule, nameOccName, isImplicitName, mkExternalName )
75 import TyCon ( tyConHasGenerics )
76 import SrcLoc ( srcLocSpan, Located(..), noLoc )
77 import DriverPhases ( HscSource(..), isHsBoot )
78 import HscTypes ( ModGuts(..), ModDetails(..), emptyModDetails,
79 HscEnv(..), ExternalPackageState(..),
80 IsBootInterface, noDependencies,
81 Deprecs( NoDeprecs ), plusDeprecs,
82 ForeignStubs(NoStubs),
83 TypeEnv, lookupTypeEnv, hptInstances,
84 extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons, typeEnvElts,
90 import HsSyn ( HsStmtContext(..), Stmt(..), HsExpr(..),
91 HsLocalBinds(..), HsValBinds(..),
92 LStmt, LHsExpr, LHsType, mkMatch, emptyLocalBinds,
93 collectLStmtsBinders, collectLStmtBinders, nlVarPat,
94 mkFunBind, placeHolderType, noSyntaxExpr, nlHsTyApp )
95 import RdrName ( GlobalRdrElt(..), globalRdrEnvElts,
96 unQualOK, lookupLocalRdrEnv, extendLocalRdrEnv )
97 import RnSource ( addTcgDUs )
98 import TcHsSyn ( mkHsDictLet, zonkTopLExpr, zonkTopBndrs )
99 import TcHsType ( kcHsType )
100 import TcMType ( zonkTcType, zonkQuantifiedTyVar )
101 import TcMatches ( tcStmts, tcDoStmt )
102 import TcSimplify ( tcSimplifyInteractive, tcSimplifyInfer )
103 import TcGadt ( emptyRefinement )
104 import TcType ( Type, mkForAllTys, mkFunTys, mkTyConApp, tyVarsOfType, isTauTy,
105 isUnLiftedType, tyClsNamesOfDFunHead, tyClsNamesOfType, isUnitTy )
106 import TcEnv ( tcLookupTyCon, tcLookupId, tcLookupGlobal )
107 import TypeRep ( TyThing(..) )
108 import RnTypes ( rnLHsType )
109 import Inst ( tcGetInstEnvs )
110 import InstEnv ( classInstances, instEnvElts )
111 import RnExpr ( rnStmts, rnLExpr )
112 import LoadIface ( loadSysInterface )
113 import IfaceEnv ( ifaceExportNames )
114 import RnEnv ( lookupOccRn, dataTcOccs, lookupFixityRn )
115 import Id ( setIdType )
116 import MkId ( unsafeCoerceId )
117 import TyCon ( tyConName )
118 import TysWiredIn ( mkListTy, unitTy )
119 import IdInfo ( GlobalIdDetails(..) )
120 import {- Kind parts of -} Type ( Kind )
121 import Var ( globaliseId )
122 import Name ( isBuiltInSyntax, isInternalName )
123 import OccName ( isTcOcc )
124 import NameEnv ( delListFromNameEnv )
125 import PrelNames ( iNTERACTIVE, ioTyConName, printName, itName,
126 bindIOName, thenIOName, returnIOName )
127 import HscTypes ( InteractiveContext(..),
128 ModIface(..), icPrintUnqual,
130 import BasicTypes ( Fixity, RecFlag(..) )
131 import SrcLoc ( unLoc )
132 import Data.Maybe ( isNothing )
135 import FastString ( mkFastString )
136 import Util ( sortLe )
137 import Bag ( unionBags, snocBag, emptyBag, unitBag, unionManyBags )
139 import Control.Monad ( unless )
140 import Data.Maybe ( isJust )
145 %************************************************************************
147 Typecheck and rename a module
149 %************************************************************************
155 -> Bool -- True <=> save renamed syntax
156 -> Located (HsModule RdrName)
157 -> IO (Messages, Maybe TcGblEnv)
159 tcRnModule hsc_env hsc_src save_rn_syntax
160 (L loc (HsModule maybe_mod export_ies
161 import_decls local_decls mod_deprec _ module_info maybe_doc))
162 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
164 let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
165 this_mod = case maybe_mod of
166 Nothing -> mAIN -- 'module M where' is omitted
167 Just (L _ mod) -> mkModule this_pkg mod } ;
170 initTc hsc_env hsc_src this_mod $
173 -- Deal with imports;
174 rn_imports <- rnImports import_decls ;
175 (rdr_env, imports) <- mkRdrEnvAndImports rn_imports ;
177 let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
178 ; dep_mods = imp_dep_mods imports
180 -- We want instance declarations from all home-package
181 -- modules below this one, including boot modules, except
182 -- ourselves. The 'except ourselves' is so that we don't
183 -- get the instances from this module's hs-boot file
184 ; want_instances :: ModuleName -> Bool
185 ; want_instances mod = mod `elemUFM` dep_mods
186 && mod /= moduleName this_mod
187 ; home_insts = hptInstances hsc_env want_instances
190 -- Record boot-file info in the EPS, so that it's
191 -- visible to loadHiBootInterface in tcRnSrcDecls,
192 -- and any other incrementally-performed imports
193 updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
195 -- Update the gbl env
197 gbl { tcg_rdr_env = plusOccEnv (tcg_rdr_env gbl) rdr_env,
198 tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
199 tcg_imports = tcg_imports gbl `plusImportAvails` imports,
200 tcg_rn_imports = if save_rn_syntax then
204 tcg_rn_decls = if save_rn_syntax then
210 traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
211 -- Fail if there are any errors so far
212 -- The error printing (if needed) takes advantage
213 -- of the tcg_env we have now set
216 -- Load any orphan-module interfaces, so that
217 -- their rules and instance decls will be found
218 loadOrphanModules (imp_orphs imports) ;
220 traceRn (text "rn1a") ;
221 -- Rename and type check the declarations
222 tcg_env <- if isHsBoot hsc_src then
223 tcRnHsBootDecls local_decls
225 tcRnSrcDecls local_decls ;
226 setGblEnv tcg_env $ do {
228 traceRn (text "rn3") ;
230 -- Report the use of any deprecated things
231 -- We do this before processsing the export list so
232 -- that we don't bleat about re-exporting a deprecated
233 -- thing (especially via 'module Foo' export item)
234 -- Only uses in the body of the module are complained about
235 reportDeprecations (hsc_dflags hsc_env) tcg_env ;
237 -- Process the export list
238 rn_exports <- rnExports export_ies ;
240 -- Rename the Haddock documentation header
241 rn_module_doc <- rnMbHsDoc maybe_doc ;
243 -- Rename the Haddock module info
244 rn_description <- rnMbHsDoc (hmi_description module_info) ;
245 let { rn_module_info = module_info { hmi_description = rn_description } } ;
247 let { liftM2' fn a b = do a' <- a; b' <- b; return (fn a' b') } ;
248 exports <- mkExportNameSet (isJust maybe_mod)
249 (liftM2' (,) rn_exports export_ies) ;
251 -- Check whether the entire module is deprecated
252 -- This happens only once per module
253 let { mod_deprecs = checkModDeprec mod_deprec } ;
255 -- Add exports and deprecations to envt
256 let { final_env = tcg_env { tcg_exports = exports,
257 tcg_rn_exports = if save_rn_syntax then
260 tcg_dus = tcg_dus tcg_env `plusDU` usesOnly exports,
261 tcg_deprecs = tcg_deprecs tcg_env `plusDeprecs`
263 tcg_doc = rn_module_doc,
264 tcg_hmi = rn_module_info
266 -- A module deprecation over-rides the earlier ones
269 -- Report unused names
270 reportUnusedNames export_ies final_env ;
272 -- Dump output and return
279 %************************************************************************
281 Type-checking external-core modules
283 %************************************************************************
286 tcRnExtCore :: HscEnv
288 -> IO (Messages, Maybe ModGuts)
289 -- Nothing => some error occurred
291 tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
292 -- The decls are IfaceDecls; all names are original names
293 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
295 initTc hsc_env ExtCoreFile this_mod $ do {
297 let { ldecls = map noLoc decls } ;
299 -- Deal with the type declarations; first bring their stuff
300 -- into scope, then rname them, then type check them
301 tcg_env <- importsFromLocalDecls (mkFakeGroup ldecls) ;
303 setGblEnv tcg_env $ do {
305 rn_decls <- rnTyClDecls ldecls ;
308 -- Dump trace of renaming part
309 rnDump (ppr rn_decls) ;
311 -- Typecheck them all together so that
312 -- any mutually recursive types are done right
313 tcg_env <- checkNoErrs (tcTyAndClassDecls emptyModDetails rn_decls) ;
314 -- Make the new type env available to stuff slurped from interface files
316 setGblEnv tcg_env $ do {
318 -- Now the core bindings
319 core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
323 bndrs = bindersOfBinds core_binds ;
324 my_exports = mkNameSet (map idName bndrs) ;
325 -- ToDo: export the data types also?
327 final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
329 mod_guts = ModGuts { mg_module = this_mod,
331 mg_usages = [], -- ToDo: compute usage
332 mg_dir_imps = [], -- ??
333 mg_deps = noDependencies, -- ??
334 mg_exports = my_exports,
335 mg_types = final_type_env,
336 mg_insts = tcg_insts tcg_env,
337 mg_fam_insts = tcg_fam_insts tcg_env,
339 mg_binds = core_binds,
342 mg_rdr_env = emptyGlobalRdrEnv,
343 mg_fix_env = emptyFixityEnv,
344 mg_deprecs = NoDeprecs,
348 tcCoreDump mod_guts ;
353 mkFakeGroup decls -- Rather clumsy; lots of unused fields
354 = emptyRdrGroup { hs_tyclds = decls }
358 %************************************************************************
360 Type-checking the top level of a module
362 %************************************************************************
365 tcRnSrcDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
366 -- Returns the variables free in the decls
367 -- Reason: solely to report unused imports and bindings
369 = do { -- Load the hi-boot interface for this module, if any
370 -- We do this now so that the boot_names can be passed
371 -- to tcTyAndClassDecls, because the boot_names are
372 -- automatically considered to be loop breakers
374 boot_iface <- tcHiBootIface mod ;
376 -- Do all the declarations
377 (tc_envs, lie) <- getLIE (tc_rn_src_decls boot_iface decls) ;
379 -- tcSimplifyTop deals with constant or ambiguous InstIds.
380 -- How could there be ambiguous ones? They can only arise if a
381 -- top-level decl falls under the monomorphism
382 -- restriction, and no subsequent decl instantiates its
383 -- type. (Usually, ambiguous type variables are resolved
384 -- during the generalisation step.)
385 traceTc (text "Tc8") ;
386 inst_binds <- setEnvs tc_envs (tcSimplifyTop lie) ;
387 -- Setting the global env exposes the instances to tcSimplifyTop
388 -- Setting the local env exposes the local Ids to tcSimplifyTop,
389 -- so that we get better error messages (monomorphism restriction)
391 -- Backsubstitution. This must be done last.
392 -- Even tcSimplifyTop may do some unification.
393 traceTc (text "Tc9") ;
394 let { (tcg_env, _) = tc_envs ;
395 TcGblEnv { tcg_type_env = type_env, tcg_binds = binds,
396 tcg_rules = rules, tcg_fords = fords } = tcg_env } ;
398 (bind_ids, binds', fords', rules') <- zonkTopDecls (binds `unionBags` inst_binds)
401 let { final_type_env = extendTypeEnvWithIds type_env bind_ids
402 ; tcg_env' = tcg_env { tcg_type_env = final_type_env,
405 tcg_fords = fords' } } ;
407 -- Make the new type env available to stuff slurped from interface files
408 writeMutVar (tcg_type_env_var tcg_env) final_type_env ;
410 -- Compare the hi-boot iface (if any) with the real thing
411 dfun_binds <- checkHiBootIface tcg_env' boot_iface ;
413 return (tcg_env' { tcg_binds = tcg_binds tcg_env' `unionBags` dfun_binds })
416 tc_rn_src_decls :: ModDetails -> [LHsDecl RdrName] -> TcM (TcGblEnv, TcLclEnv)
417 -- Loops around dealing with each top level inter-splice group
418 -- in turn, until it's dealt with the entire module
419 tc_rn_src_decls boot_details ds
420 = do { let { (first_group, group_tail) = findSplice ds } ;
421 -- If ds is [] we get ([], Nothing)
423 -- Type check the decls up to, but not including, the first splice
424 tc_envs@(tcg_env,tcl_env) <- tcRnGroup boot_details first_group ;
426 -- Bale out if errors; for example, error recovery when checking
427 -- the RHS of 'main' can mean that 'main' is not in the envt for
428 -- the subsequent checkMain test
433 -- If there is no splice, we're nearly done
435 Nothing -> do { -- Last thing: check for `main'
436 tcg_env <- checkMain ;
437 return (tcg_env, tcl_env)
440 -- If there's a splice, we must carry on
441 Just (SpliceDecl splice_expr, rest_ds) -> do {
443 failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
446 -- Rename the splice expression, and get its supporting decls
447 (rn_splice_expr, splice_fvs) <- rnLExpr splice_expr ;
448 failIfErrsM ; -- Don't typecheck if renaming failed
449 rnDump (ppr rn_splice_expr) ;
451 -- Execute the splice
452 spliced_decls <- tcSpliceDecls rn_splice_expr ;
454 -- Glue them on the front of the remaining decls and loop
455 setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
456 tc_rn_src_decls boot_details (spliced_decls ++ rest_ds)
461 %************************************************************************
463 Compiling hs-boot source files, and
464 comparing the hi-boot interface with the real thing
466 %************************************************************************
469 tcRnHsBootDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
470 tcRnHsBootDecls decls
471 = do { let { (first_group, group_tail) = findSplice decls }
474 Just stuff -> spliceInHsBootErr stuff
477 -- Rename the declarations
478 ; (tcg_env, rn_group) <- rnTopSrcDecls first_group
479 ; setGblEnv tcg_env $ do {
481 -- Todo: check no foreign decls, no rules, no default decls
483 -- Typecheck type/class decls
484 ; traceTc (text "Tc2")
485 ; let tycl_decls = hs_tyclds rn_group
486 ; tcg_env <- checkNoErrs (tcTyAndClassDecls emptyModDetails tycl_decls)
487 ; setGblEnv tcg_env $ do {
489 -- Typecheck instance decls
490 ; traceTc (text "Tc3")
491 ; (tcg_env, inst_infos, _binds)
492 <- tcInstDecls1 tycl_decls (hs_instds rn_group) (hs_derivds rn_group)
493 ; setGblEnv tcg_env $ do {
495 -- Typecheck value declarations
496 ; traceTc (text "Tc5")
497 ; val_ids <- tcHsBootSigs (hs_valds rn_group)
500 -- No simplification or zonking to do
501 ; traceTc (text "Tc7a")
502 ; gbl_env <- getGblEnv
504 -- Make the final type-env
505 -- Include the dfun_ids so that their type sigs get
506 -- are written into the interface file
507 ; let { type_env0 = tcg_type_env gbl_env
508 ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
509 ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
510 ; dfun_ids = map iDFunId inst_infos }
511 ; return (gbl_env { tcg_type_env = type_env2 })
514 spliceInHsBootErr (SpliceDecl (L loc _), _)
515 = addErrAt loc (ptext SLIT("Splices are not allowed in hs-boot files"))
518 Once we've typechecked the body of the module, we want to compare what
519 we've found (gathered in a TypeEnv) with the hi-boot details (if any).
522 checkHiBootIface :: TcGblEnv -> ModDetails -> TcM (LHsBinds Id)
523 -- Compare the hi-boot file for this module (if there is one)
524 -- with the type environment we've just come up with
525 -- In the common case where there is no hi-boot file, the list
526 -- of boot_names is empty.
528 -- The bindings we return give bindings for the dfuns defined in the
529 -- hs-boot file, such as $fbEqT = $fEqT
532 (TcGblEnv { tcg_insts = local_insts, tcg_fam_insts = local_fam_insts,
533 tcg_type_env = local_type_env })
534 (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
535 md_types = boot_type_env })
536 = do { traceTc (text "checkHiBootIface" <+> (ppr boot_type_env $$ ppr boot_insts)) ;
537 ; mapM_ check_one (typeEnvElts boot_type_env)
538 ; dfun_binds <- mapM check_inst boot_insts
539 ; unless (null boot_fam_insts) $
540 panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
541 "instances in boot files yet...")
542 -- FIXME: Why? The actual comparison is not hard, but what would
543 -- be the equivalent to the dfun bindings returned for class
544 -- instances? We can't easily equate tycons...
545 ; return (unionManyBags dfun_binds) }
550 | Just real_thing <- lookupTypeEnv local_type_env name
551 = do { let boot_decl = tyThingToIfaceDecl ext_nm boot_thing
552 real_decl = tyThingToIfaceDecl ext_nm real_thing
553 ; checkTc (checkBootDecl boot_decl real_decl)
554 (bootMisMatch boot_thing boot_decl real_decl) }
555 -- The easiest way to check compatibility is to convert to
556 -- iface syntax, where we already have good comparison functions
558 = addErrTc (missingBootThing boot_thing)
560 name = getName boot_thing
562 ext_nm name = ExtPkg (nameModule name) (nameOccName name)
563 -- Just enough to compare; no versions etc needed
565 no_check name = isWiredInName name -- No checking for wired-in names. In particular,
566 -- 'error' is handled by a rather gross hack
567 -- (see comments in GHC.Err.hs-boot)
568 || name `elem` dfun_names
569 || isImplicitName name -- Has a parent, which we'll check
571 dfun_names = map getName boot_insts
574 = case [dfun | inst <- local_insts,
575 let dfun = instanceDFunId inst,
576 idType dfun `tcEqType` boot_inst_ty ] of
577 [] -> do { addErrTc (instMisMatch boot_inst); return emptyBag }
578 (dfun:_) -> return (unitBag $ noLoc $ VarBind local_boot_dfun (nlHsVar dfun))
580 boot_dfun = instanceDFunId boot_inst
581 boot_inst_ty = idType boot_dfun
582 local_boot_dfun = mkExportedLocalId (idName boot_dfun) boot_inst_ty
585 missingBootThing thing
586 = ppr thing <+> ptext SLIT("is defined in the hs-boot file, but not in the module")
587 bootMisMatch thing boot_decl real_decl
588 = vcat [ppr thing <+> ptext SLIT("has conflicting definitions in the module and its hs-boot file"),
589 ptext SLIT("Decl") <+> ppr real_decl,
590 ptext SLIT("Boot file:") <+> ppr boot_decl]
593 2 (ptext SLIT("is defined in the hs-boot file, but not in the module"))
597 %************************************************************************
599 Type-checking the top level of a module
601 %************************************************************************
603 tcRnGroup takes a bunch of top-level source-code declarations, and
605 * gets supporting declarations from interface files
608 * and augments the TcGblEnv with the results
610 In Template Haskell it may be called repeatedly for each group of
611 declarations. It expects there to be an incoming TcGblEnv in the
612 monad; it augments it and returns the new TcGblEnv.
615 tcRnGroup :: ModDetails -> HsGroup RdrName -> TcM (TcGblEnv, TcLclEnv)
616 -- Returns the variables free in the decls, for unused-binding reporting
617 tcRnGroup boot_details decls
618 = do { -- Rename the declarations
619 (tcg_env, rn_decls) <- rnTopSrcDecls decls ;
620 setGblEnv tcg_env $ do {
622 -- Typecheck the declarations
623 tcTopSrcDecls boot_details rn_decls
626 ------------------------------------------------
627 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
629 = do { -- Bring top level binders into scope
630 tcg_env <- importsFromLocalDecls group ;
631 setGblEnv tcg_env $ do {
633 failIfErrsM ; -- No point in continuing if (say) we have duplicate declarations
635 -- Rename the source decls
636 (tcg_env, rn_decls) <- rnSrcDecls group ;
639 -- save the renamed syntax, if we want it
641 | Just grp <- tcg_rn_decls tcg_env
642 = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
646 -- Dump trace of renaming part
647 rnDump (ppr rn_decls) ;
649 return (tcg_env', rn_decls)
652 ------------------------------------------------
653 tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
654 tcTopSrcDecls boot_details
655 (HsGroup { hs_tyclds = tycl_decls,
656 hs_instds = inst_decls,
657 hs_derivds = deriv_decls,
658 hs_fords = foreign_decls,
659 hs_defds = default_decls,
660 hs_ruleds = rule_decls,
661 hs_valds = val_binds })
662 = do { -- Type-check the type and class decls, and all imported decls
663 -- The latter come in via tycl_decls
664 traceTc (text "Tc2") ;
666 tcg_env <- checkNoErrs (tcTyAndClassDecls boot_details tycl_decls) ;
667 -- tcTyAndClassDecls recovers internally, but if anything gave rise to
668 -- an error we'd better stop now, to avoid a cascade
670 -- Make these type and class decls available to stuff slurped from interface files
671 writeMutVar (tcg_type_env_var tcg_env) (tcg_type_env tcg_env) ;
674 setGblEnv tcg_env $ do {
675 -- Source-language instances, including derivings,
676 -- and import the supporting declarations
677 traceTc (text "Tc3") ;
678 (tcg_env, inst_infos, deriv_binds)
679 <- tcInstDecls1 tycl_decls inst_decls deriv_decls;
680 setGblEnv tcg_env $ do {
682 -- Foreign import declarations next. No zonking necessary
683 -- here; we can tuck them straight into the global environment.
684 traceTc (text "Tc4") ;
685 (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
686 tcExtendGlobalValEnv fi_ids $ do {
688 -- Default declarations
689 traceTc (text "Tc4a") ;
690 default_tys <- tcDefaults default_decls ;
691 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
693 -- Value declarations next
694 -- We also typecheck any extra binds that came out
695 -- of the "deriving" process (deriv_binds)
696 traceTc (text "Tc5") ;
697 (tc_val_binds, tcl_env) <- tcTopBinds (val_binds `plusHsValBinds` deriv_binds) ;
698 setLclTypeEnv tcl_env $ do {
700 -- Second pass over class and instance declarations,
701 traceTc (text "Tc6") ;
702 (inst_binds, tcl_env) <- tcInstDecls2 tycl_decls inst_infos ;
703 showLIE (text "after instDecls2") ;
706 -- They need to be zonked, so we return them
707 traceTc (text "Tc7") ;
708 (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
711 rules <- tcRules rule_decls ;
714 traceTc (text "Tc7a") ;
715 tcg_env <- getGblEnv ;
716 let { all_binds = tc_val_binds `unionBags`
717 inst_binds `unionBags`
720 -- Extend the GblEnv with the (as yet un-zonked)
721 -- bindings, rules, foreign decls
722 tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds,
723 tcg_rules = tcg_rules tcg_env ++ rules,
724 tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
725 return (tcg_env', tcl_env)
730 %************************************************************************
734 %************************************************************************
737 checkMain :: TcM TcGblEnv
738 -- If we are in module Main, check that 'main' is defined.
740 = do { ghc_mode <- getGhcMode ;
741 tcg_env <- getGblEnv ;
743 let { main_mod = mainModIs dflags ;
744 main_fn = case mainFunIs dflags of {
745 Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn)) ;
746 Nothing -> main_RDR_Unqual } } ;
748 check_main ghc_mode tcg_env main_mod main_fn
752 check_main ghc_mode tcg_env main_mod main_fn
754 = traceTc (text "checkMain not" <+> ppr main_mod <+> ppr mod) >>
758 = addErrCtxt mainCtxt $
759 do { mb_main <- lookupSrcOcc_maybe main_fn
760 -- Check that 'main' is in scope
761 -- It might be imported from another module!
763 Nothing -> do { traceTc (text "checkMain fail" <+> ppr main_mod <+> ppr main_fn)
767 { traceTc (text "checkMain found" <+> ppr main_mod <+> ppr main_fn)
768 ; let { rhs = nlHsApp (nlHsVar runMainIOName) (nlHsVar main_name) }
769 -- :Main.main :: IO () = runMainIO main
771 ; (main_expr, ty) <- setSrcSpan (srcLocSpan (getSrcLoc main_name)) $
774 -- The function that the RTS invokes is always :Main.main,
775 -- which we call root_main_id.
776 -- (Because GHC allows the user to have a module not called
777 -- Main as the main module, we can't rely on the main function
778 -- being called "Main.main". That's why root_main_id has a fixed
780 -- We also make root_main_id an implicit Id, by making main_name
781 -- its parent (hence (Just main_name)). That has the effect
782 -- of preventing its type and unfolding from getting out into
783 -- the interface file. Otherwise we can end up with two defns
784 -- for 'main' in the interface file!
786 ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
787 (mkVarOccFS FSLIT("main"))
788 (Just main_name) (getSrcLoc main_name)
789 ; root_main_id = mkExportedLocalId root_main_name ty
790 ; main_bind = noLoc (VarBind root_main_id main_expr) }
792 ; return (tcg_env { tcg_binds = tcg_binds tcg_env
794 tcg_dus = tcg_dus tcg_env
795 `plusDU` usesOnly (unitFV main_name)
796 -- Record the use of 'main', so that we don't
797 -- complain about it being defined but not used
801 mod = tcg_mod tcg_env
803 complain_no_main | ghc_mode == Interactive = return ()
804 | otherwise = failWithTc noMainMsg
805 -- In interactive mode, don't worry about the absence of 'main'
806 -- In other modes, fail altogether, so that we don't go on
807 -- and complain a second time when processing the export list.
809 mainCtxt = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
810 noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn)
811 <+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
814 %*********************************************************
818 %*********************************************************
822 setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
823 setInteractiveContext hsc_env icxt thing_inside
825 -- Initialise the tcg_inst_env with instances
826 -- from all home modules. This mimics the more selective
827 -- call to hptInstances in tcRnModule
828 dfuns = hptInstances hsc_env (\mod -> True)
830 updGblEnv (\env -> env {
831 tcg_rdr_env = ic_rn_gbl_env icxt,
832 tcg_type_env = ic_type_env icxt,
833 tcg_inst_env = extendInstEnvList (tcg_inst_env env) dfuns }) $
835 updLclEnv (\env -> env { tcl_rdr = ic_rn_local_env icxt }) $
837 do { traceTc (text "setIC" <+> ppr (ic_type_env icxt))
844 -> InteractiveContext
846 -> IO (Maybe (InteractiveContext, [Name], LHsExpr Id))
847 -- The returned [Name] is the same as the input except for
848 -- ExprStmt, in which case the returned [Name] is [itName]
850 -- The returned TypecheckedHsExpr is of type IO [ () ],
851 -- a list of the bound values, coerced to ().
853 tcRnStmt hsc_env ictxt rdr_stmt
854 = initTcPrintErrors hsc_env iNTERACTIVE $
855 setInteractiveContext hsc_env ictxt $ do {
857 -- Rename; use CmdLineMode because tcRnStmt is only used interactively
858 (([rn_stmt], _), fvs) <- rnStmts DoExpr [rdr_stmt] (return ((), emptyFVs)) ;
859 traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
862 -- The real work is done here
863 (bound_ids, tc_expr) <- mkPlan rn_stmt ;
864 zonked_expr <- zonkTopLExpr tc_expr ;
865 zonked_ids <- zonkTopBndrs bound_ids ;
867 -- None of the Ids should be of unboxed type, because we
868 -- cast them all to HValues in the end!
869 mappM bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
871 traceTc (text "tcs 1") ;
872 let { -- (a) Make all the bound ids "global" ids, now that
873 -- they're notionally top-level bindings. This is
874 -- important: otherwise when we come to compile an expression
875 -- using these ids later, the byte code generator will consider
876 -- the occurrences to be free rather than global.
878 -- (b) Tidy their types; this is important, because :info may
879 -- ask to look at them, and :info expects the things it looks
880 -- up to have tidy types
881 global_ids = map globaliseAndTidy zonked_ids ;
883 -- Update the interactive context
884 rn_env = ic_rn_local_env ictxt ;
885 type_env = ic_type_env ictxt ;
887 bound_names = map idName global_ids ;
888 new_rn_env = extendLocalRdrEnv rn_env bound_names ;
890 {- ---------------------------------------------
891 At one stage I removed any shadowed bindings from the type_env;
892 they are inaccessible but might, I suppose, cause a space leak if we leave them there.
893 However, with Template Haskell they aren't necessarily inaccessible. Consider this
895 Prelude> let f n = n * 2 :: Int
896 Prelude> fName <- runQ [| f |]
897 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
899 Prelude> let f n = n * 3 :: Int
900 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
901 In the last line we use 'fName', which resolves to the *first* 'f'
902 in scope. If we delete it from the type env, GHCi crashes because
903 it doesn't expect that.
905 Hence this code is commented out
907 shadowed = [ n | name <- bound_names,
908 let rdr_name = mkRdrUnqual (nameOccName name),
909 Just n <- [lookupLocalRdrEnv rn_env rdr_name] ] ;
910 filtered_type_env = delListFromNameEnv type_env shadowed ;
911 -------------------------------------------------- -}
913 new_type_env = extendTypeEnvWithIds type_env global_ids ;
914 new_ic = ictxt { ic_rn_local_env = new_rn_env,
915 ic_type_env = new_type_env }
918 dumpOptTcRn Opt_D_dump_tc
919 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
920 text "Typechecked expr" <+> ppr zonked_expr]) ;
922 returnM (new_ic, bound_names, zonked_expr)
925 bad_unboxed id = addErr (sep [ptext SLIT("GHCi can't bind a variable of unlifted type:"),
926 nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
928 globaliseAndTidy :: Id -> Id
930 -- Give the Id a Global Name, and tidy its type
931 = setIdType (globaliseId VanillaGlobal id) tidy_type
933 tidy_type = tidyTopType (idType id)
936 Here is the grand plan, implemented in tcUserStmt
938 What you type The IO [HValue] that hscStmt returns
939 ------------- ------------------------------------
940 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
943 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
946 expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
947 [NB: result not printed] bindings: [it]
949 expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
950 result showable) bindings: [it]
952 expr (of non-IO type,
953 result not showable) ==> error
957 ---------------------------
958 type PlanResult = ([Id], LHsExpr Id)
959 type Plan = TcM PlanResult
961 runPlans :: [Plan] -> TcM PlanResult
962 -- Try the plans in order. If one fails (by raising an exn), try the next.
963 -- If one succeeds, take it.
964 runPlans [] = panic "runPlans"
966 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
969 mkPlan :: LStmt Name -> TcM PlanResult
970 mkPlan (L loc (ExprStmt expr _ _)) -- An expression typed at the prompt
971 = do { uniq <- newUnique -- is treated very specially
972 ; let fresh_it = itName uniq
973 the_bind = L loc $ mkFunBind (L loc fresh_it) matches
974 matches = [mkMatch [] expr emptyLocalBinds]
975 let_stmt = L loc $ LetStmt (HsValBinds (ValBindsOut [(NonRecursive,unitBag the_bind)] []))
976 bind_stmt = L loc $ BindStmt (nlVarPat fresh_it) expr
977 (HsVar bindIOName) noSyntaxExpr
978 print_it = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar fresh_it))
979 (HsVar thenIOName) placeHolderType
982 -- [it <- e; print it] but not if it::()
984 -- [let it = e; print it]
985 ; runPlans [ -- Plan A
986 do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
987 ; it_ty <- zonkTcType (idType it_id)
988 ; ifM (isUnitTy it_ty) failM
991 -- Plan B; a naked bind statment
992 tcGhciStmts [bind_stmt],
994 -- Plan C; check that the let-binding is typeable all by itself.
995 -- If not, fail; if so, try to print it.
996 -- The two-step process avoids getting two errors: one from
997 -- the expression itself, and one from the 'print it' part
998 -- This two-step story is very clunky, alas
999 do { checkNoErrs (tcGhciStmts [let_stmt])
1000 --- checkNoErrs defeats the error recovery of let-bindings
1001 ; tcGhciStmts [let_stmt, print_it] }
1004 mkPlan stmt@(L loc (BindStmt {}))
1005 | [L _ v] <- collectLStmtBinders stmt -- One binder, for a bind stmt
1006 = do { let print_v = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
1007 (HsVar thenIOName) placeHolderType
1009 ; print_bind_result <- doptM Opt_PrintBindResult
1010 ; let print_plan = do
1011 { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
1012 ; v_ty <- zonkTcType (idType v_id)
1013 ; ifM (isUnitTy v_ty || not (isTauTy v_ty)) failM
1017 -- [stmt; print v] but not if v::()
1019 ; runPlans ((if print_bind_result then [print_plan] else []) ++
1020 [tcGhciStmts [stmt]])
1024 = tcGhciStmts [stmt]
1026 ---------------------------
1027 tcGhciStmts :: [LStmt Name] -> TcM PlanResult
1029 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
1030 ret_id <- tcLookupId returnIOName ; -- return @ IO
1032 io_ty = mkTyConApp ioTyCon [] ;
1033 ret_ty = mkListTy unitTy ;
1034 io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
1035 tc_io_stmts stmts = tcStmts DoExpr (tcDoStmt io_ty) stmts
1036 (emptyRefinement, io_ret_ty) ;
1038 names = map unLoc (collectLStmtsBinders stmts) ;
1040 -- mk_return builds the expression
1041 -- returnIO @ [()] [coerce () x, .., coerce () z]
1043 -- Despite the inconvenience of building the type applications etc,
1044 -- this *has* to be done in type-annotated post-typecheck form
1045 -- because we are going to return a list of *polymorphic* values
1046 -- coerced to type (). If we built a *source* stmt
1047 -- return [coerce x, ..., coerce z]
1048 -- then the type checker would instantiate x..z, and we wouldn't
1049 -- get their *polymorphic* values. (And we'd get ambiguity errs
1050 -- if they were overloaded, since they aren't applied to anything.)
1051 mk_return ids = nlHsApp (nlHsTyApp ret_id [ret_ty])
1052 (noLoc $ ExplicitList unitTy (map mk_item ids)) ;
1053 mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
1057 -- OK, we're ready to typecheck the stmts
1058 traceTc (text "tcs 2") ;
1059 ((tc_stmts, ids), lie) <- getLIE $ tc_io_stmts stmts $ \ _ ->
1060 mappM tcLookupId names ;
1061 -- Look up the names right in the middle,
1062 -- where they will all be in scope
1064 -- Simplify the context
1065 const_binds <- checkNoErrs (tcSimplifyInteractive lie) ;
1066 -- checkNoErrs ensures that the plan fails if context redn fails
1068 return (ids, mkHsDictLet const_binds $
1069 noLoc (HsDo DoExpr tc_stmts (mk_return ids) io_ret_ty))
1074 tcRnExpr just finds the type of an expression
1078 -> InteractiveContext
1081 tcRnExpr hsc_env ictxt rdr_expr
1082 = initTcPrintErrors hsc_env iNTERACTIVE $
1083 setInteractiveContext hsc_env ictxt $ do {
1085 (rn_expr, fvs) <- rnLExpr rdr_expr ;
1088 -- Now typecheck the expression;
1089 -- it might have a rank-2 type (e.g. :t runST)
1090 ((tc_expr, res_ty), lie) <- getLIE (tcInferRho rn_expr) ;
1091 ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie) ;
1092 tcSimplifyInteractive lie_top ;
1093 qtvs' <- mappM zonkQuantifiedTyVar qtvs ;
1095 let { all_expr_ty = mkForAllTys qtvs' $
1096 mkFunTys (map idType dict_ids) $
1098 zonkTcType all_expr_ty
1101 smpl_doc = ptext SLIT("main expression")
1104 tcRnType just finds the kind of a type
1108 -> InteractiveContext
1111 tcRnType hsc_env ictxt rdr_type
1112 = initTcPrintErrors hsc_env iNTERACTIVE $
1113 setInteractiveContext hsc_env ictxt $ do {
1115 rn_type <- rnLHsType doc rdr_type ;
1118 -- Now kind-check the type
1119 (ty', kind) <- kcHsType rn_type ;
1123 doc = ptext SLIT("In GHCi input")
1129 %************************************************************************
1131 More GHCi stuff, to do with browsing and getting info
1133 %************************************************************************
1137 -- ASSUMES that the module is either in the HomePackageTable or is
1138 -- a package module with an interface on disk. If neither of these is
1139 -- true, then the result will be an error indicating the interface
1140 -- could not be found.
1141 getModuleExports :: HscEnv -> Module -> IO (Messages, Maybe NameSet)
1142 getModuleExports hsc_env mod
1143 = initTc hsc_env HsSrcFile iNTERACTIVE (tcGetModuleExports mod)
1145 tcGetModuleExports :: Module -> TcM NameSet
1146 tcGetModuleExports mod = do
1147 let doc = ptext SLIT("context for compiling statements")
1148 iface <- initIfaceTcRn $ loadSysInterface doc mod
1149 loadOrphanModules (dep_orphs (mi_deps iface))
1150 -- Load any orphan-module interfaces,
1151 -- so their instances are visible
1152 ifaceExportNames (mi_exports iface)
1154 tcRnLookupRdrName :: HscEnv -> RdrName -> IO (Maybe [Name])
1155 tcRnLookupRdrName hsc_env rdr_name
1156 = initTcPrintErrors hsc_env iNTERACTIVE $
1157 setInteractiveContext hsc_env (hsc_IC hsc_env) $
1158 lookup_rdr_name rdr_name
1160 lookup_rdr_name rdr_name = do {
1161 -- If the identifier is a constructor (begins with an
1162 -- upper-case letter), then we need to consider both
1163 -- constructor and type class identifiers.
1164 let { rdr_names = dataTcOccs rdr_name } ;
1166 -- results :: [Either Messages Name]
1167 results <- mapM (tryTcErrs . lookupOccRn) rdr_names ;
1169 traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)]);
1170 -- The successful lookups will be (Just name)
1171 let { (warns_s, good_names) = unzip [ (msgs, name)
1172 | (msgs, Just name) <- results] ;
1173 errs_s = [msgs | (msgs, Nothing) <- results] } ;
1175 -- Fail if nothing good happened, else add warnings
1176 if null good_names then
1177 -- No lookup succeeded, so
1178 -- pick the first error message and report it
1179 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
1180 -- while the other is "X is not in scope",
1181 -- we definitely want the former; but we might pick the latter
1182 do { addMessages (head errs_s) ; failM }
1183 else -- Add deprecation warnings
1184 mapM_ addMessages warns_s ;
1190 tcRnLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
1191 tcRnLookupName hsc_env name
1192 = initTcPrintErrors hsc_env iNTERACTIVE $
1193 setInteractiveContext hsc_env (hsc_IC hsc_env) $
1197 tcRnGetInfo :: HscEnv
1199 -> IO (Maybe (TyThing, Fixity, [Instance]))
1201 -- Used to implemnent :info in GHCi
1203 -- Look up a RdrName and return all the TyThings it might be
1204 -- A capitalised RdrName is given to us in the DataName namespace,
1205 -- but we want to treat it as *both* a data constructor
1206 -- *and* as a type or class constructor;
1207 -- hence the call to dataTcOccs, and we return up to two results
1208 tcRnGetInfo hsc_env name
1209 = initTcPrintErrors hsc_env iNTERACTIVE $
1210 let ictxt = hsc_IC hsc_env in
1211 setInteractiveContext hsc_env ictxt $ do
1213 -- Load the interface for all unqualified types and classes
1214 -- That way we will find all the instance declarations
1215 -- (Packages have not orphan modules, and we assume that
1216 -- in the home package all relevant modules are loaded.)
1217 loadUnqualIfaces ictxt
1219 thing <- tcLookupGlobal name
1220 fixity <- lookupFixityRn name
1221 ispecs <- lookupInsts (icPrintUnqual ictxt) thing
1222 return (thing, fixity, ispecs)
1225 lookupInsts :: PrintUnqualified -> TyThing -> TcM [Instance]
1226 -- Filter the instances by the ones whose tycons (or clases resp)
1227 -- are in scope unqualified. Otherwise we list a whole lot too many!
1228 lookupInsts print_unqual (AClass cls)
1229 = do { inst_envs <- tcGetInstEnvs
1231 | ispec <- classInstances inst_envs cls
1232 , plausibleDFun print_unqual (instanceDFunId ispec) ] }
1234 lookupInsts print_unqual (ATyCon tc)
1235 = do { eps <- getEps -- Load all instances for all classes that are
1236 -- in the type environment (which are all the ones
1237 -- we've seen in any interface file so far)
1238 ; (pkg_ie, home_ie) <- tcGetInstEnvs -- Search all
1240 | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
1241 , let dfun = instanceDFunId ispec
1243 , plausibleDFun print_unqual dfun ] }
1245 relevant df = tc_name `elemNameSet` tyClsNamesOfDFunHead (idType df)
1246 tc_name = tyConName tc
1248 lookupInsts print_unqual other = return []
1250 plausibleDFun print_unqual dfun -- Dfun involving only names that print unqualified
1251 = all ok (nameSetToList (tyClsNamesOfType (idType dfun)))
1253 ok name | isBuiltInSyntax name = True
1254 | isExternalName name =
1255 isNothing $ fst print_unqual (nameModule name)
1259 loadUnqualIfaces :: InteractiveContext -> TcM ()
1260 -- Load the home module for everything that is in scope unqualified
1261 -- This is so that we can accurately report the instances for
1263 loadUnqualIfaces ictxt
1265 mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
1267 unqual_mods = [ nameModule name
1268 | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt),
1269 let name = gre_name gre,
1270 not (isInternalName name),
1271 isTcOcc (nameOccName name), -- Types and classes only
1272 unQualOK gre ] -- In scope unqualified
1273 doc = ptext SLIT("Need interface for module whose export(s) are in scope unqualified")
1277 %************************************************************************
1281 %************************************************************************
1284 rnDump :: SDoc -> TcRn ()
1285 -- Dump, with a banner, if -ddump-rn
1286 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
1288 tcDump :: TcGblEnv -> TcRn ()
1290 = do { dflags <- getDOpts ;
1292 -- Dump short output if -ddump-types or -ddump-tc
1293 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1294 (dumpTcRn short_dump) ;
1296 -- Dump bindings if -ddump-tc
1297 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1300 short_dump = pprTcGblEnv env
1301 full_dump = pprLHsBinds (tcg_binds env)
1302 -- NB: foreign x-d's have undefined's in their types;
1303 -- hence can't show the tc_fords
1306 = do { dflags <- getDOpts ;
1307 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1308 (dumpTcRn (pprModGuts mod_guts)) ;
1310 -- Dump bindings if -ddump-tc
1311 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1313 full_dump = pprCoreBindings (mg_binds mod_guts)
1315 -- It's unpleasant having both pprModGuts and pprModDetails here
1316 pprTcGblEnv :: TcGblEnv -> SDoc
1317 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
1319 tcg_fam_insts = fam_insts,
1321 tcg_imports = imports })
1322 = vcat [ ppr_types insts type_env
1324 , ppr_fam_insts fam_insts
1325 , vcat (map ppr rules)
1326 , ppr_gen_tycons (typeEnvTyCons type_env)
1327 , ptext SLIT("Dependent modules:") <+> ppr (eltsUFM (imp_dep_mods imports))
1328 , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1330 pprModGuts :: ModGuts -> SDoc
1331 pprModGuts (ModGuts { mg_types = type_env,
1333 = vcat [ ppr_types [] type_env,
1336 ppr_types :: [Instance] -> TypeEnv -> SDoc
1337 ppr_types insts type_env
1338 = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1340 dfun_ids = map instanceDFunId insts
1341 ids = [id | id <- typeEnvIds type_env, want_sig id]
1342 want_sig id | opt_PprStyle_Debug = True
1343 | otherwise = isLocalId id &&
1344 isExternalName (idName id) &&
1345 not (id `elem` dfun_ids)
1346 -- isLocalId ignores data constructors, records selectors etc.
1347 -- The isExternalName ignores local dictionary and method bindings
1348 -- that the type checker has invented. Top-level user-defined things
1349 -- have External names.
1351 ppr_insts :: [Instance] -> SDoc
1352 ppr_insts [] = empty
1353 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
1355 ppr_fam_insts :: [FamInst] -> SDoc
1356 ppr_fam_insts [] = empty
1357 ppr_fam_insts fam_insts =
1358 text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
1360 ppr_sigs :: [Var] -> SDoc
1362 -- Print type signatures; sort by OccName
1363 = vcat (map ppr_sig (sortLe le_sig ids))
1365 le_sig id1 id2 = getOccName id1 <= getOccName id2
1366 ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1368 ppr_rules :: [CoreRule] -> SDoc
1369 ppr_rules [] = empty
1370 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1371 nest 4 (pprRules rs),
1374 ppr_gen_tycons [] = empty
1375 ppr_gen_tycons tcs = vcat [ptext SLIT("Tycons with generics:"),
1376 nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]