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 )
55 import TcSimplify ( tcSimplifyTop )
56 import TcTyClsDecls ( tcTyAndClassDecls )
57 import LoadIface ( loadOrphanModules )
58 import RnNames ( importsFromLocalDecls, rnImports, rnExports,
59 reportUnusedNames, reportDeprecations )
60 import RnEnv ( lookupSrcOcc_maybe )
61 import RnSource ( rnSrcDecls, rnTyClDecls, checkModDeprec )
62 import RnHsDoc ( rnMbHsDoc )
63 import PprCore ( pprRules, pprCoreBindings )
64 import CoreSyn ( CoreRule, bindersOfBinds )
65 import ErrUtils ( Messages, mkDumpDoc, showPass )
66 import Id ( Id, mkExportedLocalId, isLocalId, idName, idType )
69 import UniqFM ( elemUFM, eltsUFM )
70 import OccName ( mkVarOccFS, plusOccEnv )
71 import Name ( Name, NamedThing(..), isExternalName, getSrcLoc, isWiredInName,
72 nameModule, nameOccName, 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), availsToNameSet,
83 TypeEnv, lookupTypeEnv, hptInstances,
84 extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons, typeEnvElts,
85 emptyFixityEnv, GenAvailInfo(..)
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 PrelNames ( iNTERACTIVE, ioTyConName, printName, itName,
125 bindIOName, thenIOName, returnIOName )
126 import HscTypes ( InteractiveContext(..),
127 ModIface(..), icPrintUnqual,
129 import BasicTypes ( Fixity, RecFlag(..) )
130 import SrcLoc ( unLoc )
131 import Data.Maybe ( isNothing )
134 import FastString ( mkFastString )
135 import Util ( sortLe )
136 import Bag ( unionBags, snocBag, emptyBag, unitBag, unionManyBags )
138 import Control.Monad ( unless )
139 import Data.Maybe ( isJust )
144 %************************************************************************
146 Typecheck and rename a module
148 %************************************************************************
154 -> Bool -- True <=> save renamed syntax
155 -> Located (HsModule RdrName)
156 -> IO (Messages, Maybe TcGblEnv)
158 tcRnModule hsc_env hsc_src save_rn_syntax
159 (L loc (HsModule maybe_mod export_ies
160 import_decls local_decls mod_deprec _ module_info maybe_doc))
161 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
163 let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
164 this_mod = case maybe_mod of
165 Nothing -> mAIN -- 'module M where' is omitted
166 Just (L _ mod) -> mkModule this_pkg mod } ;
169 initTc hsc_env hsc_src this_mod $
172 -- Deal with imports;
173 (rn_imports, rdr_env, imports) <- rnImports import_decls ;
175 let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
176 ; dep_mods = imp_dep_mods imports
178 -- We want instance declarations from all home-package
179 -- modules below this one, including boot modules, except
180 -- ourselves. The 'except ourselves' is so that we don't
181 -- get the instances from this module's hs-boot file
182 ; want_instances :: ModuleName -> Bool
183 ; want_instances mod = mod `elemUFM` dep_mods
184 && mod /= moduleName this_mod
185 ; home_insts = hptInstances hsc_env want_instances
188 -- Record boot-file info in the EPS, so that it's
189 -- visible to loadHiBootInterface in tcRnSrcDecls,
190 -- and any other incrementally-performed imports
191 updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
193 -- Update the gbl env
195 gbl { tcg_rdr_env = plusOccEnv (tcg_rdr_env gbl) rdr_env,
196 tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
197 tcg_imports = tcg_imports gbl `plusImportAvails` imports,
198 tcg_rn_imports = if save_rn_syntax then
202 tcg_rn_decls = if save_rn_syntax then
208 traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
209 -- Fail if there are any errors so far
210 -- The error printing (if needed) takes advantage
211 -- of the tcg_env we have now set
212 traceIf (text "rdr_env: " <+> ppr rdr_env) ;
215 -- Load any orphan-module interfaces, so that
216 -- their rules and instance decls will be found
217 loadOrphanModules (imp_orphs imports) ;
219 traceRn (text "rn1a") ;
220 -- Rename and type check the declarations
221 tcg_env <- if isHsBoot hsc_src then
222 tcRnHsBootDecls local_decls
224 tcRnSrcDecls local_decls ;
225 setGblEnv tcg_env $ do {
227 traceRn (text "rn3") ;
229 -- Report the use of any deprecated things
230 -- We do this before processsing the export list so
231 -- that we don't bleat about re-exporting a deprecated
232 -- thing (especially via 'module Foo' export item)
233 -- Only uses in the body of the module are complained about
234 reportDeprecations (hsc_dflags hsc_env) tcg_env ;
236 -- Process the export list
237 (rn_exports, exports) <- rnExports (isJust maybe_mod) export_ies ;
239 -- Rename the Haddock documentation header
240 rn_module_doc <- rnMbHsDoc maybe_doc ;
242 -- Rename the Haddock module info
243 rn_description <- rnMbHsDoc (hmi_description module_info) ;
244 let { rn_module_info = module_info { hmi_description = rn_description } } ;
246 -- Check whether the entire module is deprecated
247 -- This happens only once per module
248 let { mod_deprecs = checkModDeprec mod_deprec } ;
250 -- Add exports and deprecations to envt
251 let { final_env = tcg_env { tcg_exports = exports,
252 tcg_rn_exports = if save_rn_syntax then
255 tcg_dus = tcg_dus tcg_env `plusDU` usesOnly (availsToNameSet exports),
256 tcg_deprecs = tcg_deprecs tcg_env `plusDeprecs`
258 tcg_doc = rn_module_doc,
259 tcg_hmi = rn_module_info
261 -- A module deprecation over-rides the earlier ones
264 -- Report unused names
265 reportUnusedNames export_ies final_env ;
267 -- Dump output and return
274 %************************************************************************
276 Type-checking external-core modules
278 %************************************************************************
281 tcRnExtCore :: HscEnv
283 -> IO (Messages, Maybe ModGuts)
284 -- Nothing => some error occurred
286 tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
287 -- The decls are IfaceDecls; all names are original names
288 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
290 initTc hsc_env ExtCoreFile this_mod $ do {
292 let { ldecls = map noLoc decls } ;
294 -- Deal with the type declarations; first bring their stuff
295 -- into scope, then rname them, then type check them
296 tcg_env <- importsFromLocalDecls (mkFakeGroup ldecls) ;
298 setGblEnv tcg_env $ do {
300 rn_decls <- rnTyClDecls ldecls ;
303 -- Dump trace of renaming part
304 rnDump (ppr rn_decls) ;
306 -- Typecheck them all together so that
307 -- any mutually recursive types are done right
308 tcg_env <- checkNoErrs (tcTyAndClassDecls emptyModDetails rn_decls) ;
309 -- Make the new type env available to stuff slurped from interface files
311 setGblEnv tcg_env $ do {
313 -- Now the core bindings
314 core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
318 bndrs = bindersOfBinds core_binds ;
319 my_exports = map (Avail . idName) bndrs ;
320 -- ToDo: export the data types also?
322 final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
324 mod_guts = ModGuts { mg_module = this_mod,
326 mg_usages = [], -- ToDo: compute usage
327 mg_dir_imps = [], -- ??
328 mg_deps = noDependencies, -- ??
329 mg_exports = my_exports,
330 mg_types = final_type_env,
331 mg_insts = tcg_insts tcg_env,
332 mg_fam_insts = tcg_fam_insts tcg_env,
334 mg_binds = core_binds,
337 mg_rdr_env = emptyGlobalRdrEnv,
338 mg_fix_env = emptyFixityEnv,
339 mg_deprecs = NoDeprecs,
343 tcCoreDump mod_guts ;
348 mkFakeGroup decls -- Rather clumsy; lots of unused fields
349 = emptyRdrGroup { hs_tyclds = decls }
353 %************************************************************************
355 Type-checking the top level of a module
357 %************************************************************************
360 tcRnSrcDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
361 -- Returns the variables free in the decls
362 -- Reason: solely to report unused imports and bindings
364 = do { -- Load the hi-boot interface for this module, if any
365 -- We do this now so that the boot_names can be passed
366 -- to tcTyAndClassDecls, because the boot_names are
367 -- automatically considered to be loop breakers
369 boot_iface <- tcHiBootIface mod ;
371 -- Do all the declarations
372 (tc_envs, lie) <- getLIE (tc_rn_src_decls boot_iface decls) ;
374 -- tcSimplifyTop deals with constant or ambiguous InstIds.
375 -- How could there be ambiguous ones? They can only arise if a
376 -- top-level decl falls under the monomorphism
377 -- restriction, and no subsequent decl instantiates its
378 -- type. (Usually, ambiguous type variables are resolved
379 -- during the generalisation step.)
380 traceTc (text "Tc8") ;
381 inst_binds <- setEnvs tc_envs (tcSimplifyTop lie) ;
382 -- Setting the global env exposes the instances to tcSimplifyTop
383 -- Setting the local env exposes the local Ids to tcSimplifyTop,
384 -- so that we get better error messages (monomorphism restriction)
386 -- Backsubstitution. This must be done last.
387 -- Even tcSimplifyTop may do some unification.
388 traceTc (text "Tc9") ;
389 let { (tcg_env, _) = tc_envs ;
390 TcGblEnv { tcg_type_env = type_env, tcg_binds = binds,
391 tcg_rules = rules, tcg_fords = fords } = tcg_env } ;
393 (bind_ids, binds', fords', rules') <- zonkTopDecls (binds `unionBags` inst_binds)
396 let { final_type_env = extendTypeEnvWithIds type_env bind_ids
397 ; tcg_env' = tcg_env { tcg_type_env = final_type_env,
400 tcg_fords = fords' } } ;
402 -- Make the new type env available to stuff slurped from interface files
403 writeMutVar (tcg_type_env_var tcg_env) final_type_env ;
405 -- Compare the hi-boot iface (if any) with the real thing
406 dfun_binds <- checkHiBootIface tcg_env' boot_iface ;
408 return (tcg_env' { tcg_binds = tcg_binds tcg_env' `unionBags` dfun_binds })
411 tc_rn_src_decls :: ModDetails -> [LHsDecl RdrName] -> TcM (TcGblEnv, TcLclEnv)
412 -- Loops around dealing with each top level inter-splice group
413 -- in turn, until it's dealt with the entire module
414 tc_rn_src_decls boot_details ds
415 = do { let { (first_group, group_tail) = findSplice ds } ;
416 -- If ds is [] we get ([], Nothing)
418 -- Type check the decls up to, but not including, the first splice
419 tc_envs@(tcg_env,tcl_env) <- tcRnGroup boot_details first_group ;
421 -- Bale out if errors; for example, error recovery when checking
422 -- the RHS of 'main' can mean that 'main' is not in the envt for
423 -- the subsequent checkMain test
428 -- If there is no splice, we're nearly done
430 Nothing -> do { -- Last thing: check for `main'
431 tcg_env <- checkMain ;
432 return (tcg_env, tcl_env)
435 -- If there's a splice, we must carry on
436 Just (SpliceDecl splice_expr, rest_ds) -> do {
438 failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
441 -- Rename the splice expression, and get its supporting decls
442 (rn_splice_expr, splice_fvs) <- rnLExpr splice_expr ;
443 failIfErrsM ; -- Don't typecheck if renaming failed
444 rnDump (ppr rn_splice_expr) ;
446 -- Execute the splice
447 spliced_decls <- tcSpliceDecls rn_splice_expr ;
449 -- Glue them on the front of the remaining decls and loop
450 setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
451 tc_rn_src_decls boot_details (spliced_decls ++ rest_ds)
456 %************************************************************************
458 Compiling hs-boot source files, and
459 comparing the hi-boot interface with the real thing
461 %************************************************************************
464 tcRnHsBootDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
465 tcRnHsBootDecls decls
466 = do { let { (first_group, group_tail) = findSplice decls }
469 Just stuff -> spliceInHsBootErr stuff
472 -- Rename the declarations
473 ; (tcg_env, rn_group) <- rnTopSrcDecls first_group
474 ; setGblEnv tcg_env $ do {
476 -- Todo: check no foreign decls, no rules, no default decls
478 -- Typecheck type/class decls
479 ; traceTc (text "Tc2")
480 ; let tycl_decls = hs_tyclds rn_group
481 ; tcg_env <- checkNoErrs (tcTyAndClassDecls emptyModDetails tycl_decls)
482 ; setGblEnv tcg_env $ do {
484 -- Typecheck instance decls
485 ; traceTc (text "Tc3")
486 ; (tcg_env, inst_infos, _binds)
487 <- tcInstDecls1 tycl_decls (hs_instds rn_group) (hs_derivds rn_group)
488 ; setGblEnv tcg_env $ do {
490 -- Typecheck value declarations
491 ; traceTc (text "Tc5")
492 ; val_ids <- tcHsBootSigs (hs_valds rn_group)
495 -- No simplification or zonking to do
496 ; traceTc (text "Tc7a")
497 ; gbl_env <- getGblEnv
499 -- Make the final type-env
500 -- Include the dfun_ids so that their type sigs get
501 -- are written into the interface file
502 ; let { type_env0 = tcg_type_env gbl_env
503 ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
504 ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
505 ; dfun_ids = map iDFunId inst_infos }
506 ; return (gbl_env { tcg_type_env = type_env2 })
509 spliceInHsBootErr (SpliceDecl (L loc _), _)
510 = addErrAt loc (ptext SLIT("Splices are not allowed in hs-boot files"))
513 Once we've typechecked the body of the module, we want to compare what
514 we've found (gathered in a TypeEnv) with the hi-boot details (if any).
517 checkHiBootIface :: TcGblEnv -> ModDetails -> TcM (LHsBinds Id)
518 -- Compare the hi-boot file for this module (if there is one)
519 -- with the type environment we've just come up with
520 -- In the common case where there is no hi-boot file, the list
521 -- of boot_names is empty.
523 -- The bindings we return give bindings for the dfuns defined in the
524 -- hs-boot file, such as $fbEqT = $fEqT
527 (TcGblEnv { tcg_insts = local_insts, tcg_fam_insts = local_fam_insts,
528 tcg_type_env = local_type_env, tcg_imports = imports })
529 (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
530 md_types = boot_type_env })
531 = do { traceTc (text "checkHiBootIface" <+> (ppr boot_type_env $$ ppr boot_insts)) ;
532 ; mapM_ check_one (typeEnvElts boot_type_env)
533 ; dfun_binds <- mapM check_inst boot_insts
534 ; unless (null boot_fam_insts) $
535 panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
536 "instances in boot files yet...")
537 -- FIXME: Why? The actual comparison is not hard, but what would
538 -- be the equivalent to the dfun bindings returned for class
539 -- instances? We can't easily equate tycons...
540 ; return (unionManyBags dfun_binds) }
545 | Just real_thing <- lookupTypeEnv local_type_env name
546 = do { let boot_decl = tyThingToIfaceDecl boot_thing
547 real_decl = tyThingToIfaceDecl real_thing
548 ; checkTc (checkBootDecl boot_decl real_decl)
549 (bootMisMatch boot_thing boot_decl real_decl) }
550 -- The easiest way to check compatibility is to convert to
551 -- iface syntax, where we already have good comparison functions
553 = addErrTc (missingBootThing boot_thing)
555 name = getName boot_thing
557 avail_env = imp_parent imports
558 is_implicit name = case lookupNameEnv avail_env name of
559 Just (AvailTC tc _) | tc /= name -> True
562 no_check name = isWiredInName name -- No checking for wired-in names. In particular,
563 -- 'error' is handled by a rather gross hack
564 -- (see comments in GHC.Err.hs-boot)
565 || name `elem` dfun_names
566 || is_implicit name -- Has a parent, which we'll check
568 dfun_names = map getName boot_insts
571 = case [dfun | inst <- local_insts,
572 let dfun = instanceDFunId inst,
573 idType dfun `tcEqType` boot_inst_ty ] of
574 [] -> do { addErrTc (instMisMatch boot_inst); return emptyBag }
575 (dfun:_) -> return (unitBag $ noLoc $ VarBind local_boot_dfun (nlHsVar dfun))
577 boot_dfun = instanceDFunId boot_inst
578 boot_inst_ty = idType boot_dfun
579 local_boot_dfun = mkExportedLocalId (idName boot_dfun) boot_inst_ty
582 missingBootThing thing
583 = ppr thing <+> ptext SLIT("is defined in the hs-boot file, but not in the module")
584 bootMisMatch thing boot_decl real_decl
585 = vcat [ppr thing <+> ptext SLIT("has conflicting definitions in the module and its hs-boot file"),
586 ptext SLIT("Decl") <+> ppr real_decl,
587 ptext SLIT("Boot file:") <+> ppr boot_decl]
590 2 (ptext SLIT("is defined in the hs-boot file, but not in the module"))
594 %************************************************************************
596 Type-checking the top level of a module
598 %************************************************************************
600 tcRnGroup takes a bunch of top-level source-code declarations, and
602 * gets supporting declarations from interface files
605 * and augments the TcGblEnv with the results
607 In Template Haskell it may be called repeatedly for each group of
608 declarations. It expects there to be an incoming TcGblEnv in the
609 monad; it augments it and returns the new TcGblEnv.
612 tcRnGroup :: ModDetails -> HsGroup RdrName -> TcM (TcGblEnv, TcLclEnv)
613 -- Returns the variables free in the decls, for unused-binding reporting
614 tcRnGroup boot_details decls
615 = do { -- Rename the declarations
616 (tcg_env, rn_decls) <- rnTopSrcDecls decls ;
617 setGblEnv tcg_env $ do {
619 -- Typecheck the declarations
620 tcTopSrcDecls boot_details rn_decls
623 ------------------------------------------------
624 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
626 = do { -- Bring top level binders into scope
627 tcg_env <- importsFromLocalDecls group ;
628 setGblEnv tcg_env $ do {
630 failIfErrsM ; -- No point in continuing if (say) we have duplicate declarations
632 -- Rename the source decls
633 (tcg_env, rn_decls) <- rnSrcDecls group ;
636 -- save the renamed syntax, if we want it
638 | Just grp <- tcg_rn_decls tcg_env
639 = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
643 -- Dump trace of renaming part
644 rnDump (ppr rn_decls) ;
646 return (tcg_env', rn_decls)
649 ------------------------------------------------
650 tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
651 tcTopSrcDecls boot_details
652 (HsGroup { hs_tyclds = tycl_decls,
653 hs_instds = inst_decls,
654 hs_derivds = deriv_decls,
655 hs_fords = foreign_decls,
656 hs_defds = default_decls,
657 hs_ruleds = rule_decls,
658 hs_valds = val_binds })
659 = do { -- Type-check the type and class decls, and all imported decls
660 -- The latter come in via tycl_decls
661 traceTc (text "Tc2") ;
663 tcg_env <- checkNoErrs (tcTyAndClassDecls boot_details tycl_decls) ;
664 -- tcTyAndClassDecls recovers internally, but if anything gave rise to
665 -- an error we'd better stop now, to avoid a cascade
667 -- Make these type and class decls available to stuff slurped from interface files
668 writeMutVar (tcg_type_env_var tcg_env) (tcg_type_env tcg_env) ;
671 setGblEnv tcg_env $ do {
672 -- Source-language instances, including derivings,
673 -- and import the supporting declarations
674 traceTc (text "Tc3") ;
675 (tcg_env, inst_infos, deriv_binds)
676 <- tcInstDecls1 tycl_decls inst_decls deriv_decls;
677 setGblEnv tcg_env $ do {
679 -- Foreign import declarations next. No zonking necessary
680 -- here; we can tuck them straight into the global environment.
681 traceTc (text "Tc4") ;
682 (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
683 tcExtendGlobalValEnv fi_ids $ do {
685 -- Default declarations
686 traceTc (text "Tc4a") ;
687 default_tys <- tcDefaults default_decls ;
688 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
690 -- Value declarations next
691 -- We also typecheck any extra binds that came out
692 -- of the "deriving" process (deriv_binds)
693 traceTc (text "Tc5") ;
694 (tc_val_binds, tcl_env) <- tcTopBinds (val_binds `plusHsValBinds` deriv_binds) ;
695 setLclTypeEnv tcl_env $ do {
697 -- Second pass over class and instance declarations,
698 traceTc (text "Tc6") ;
699 (inst_binds, tcl_env) <- tcInstDecls2 tycl_decls inst_infos ;
700 showLIE (text "after instDecls2") ;
703 -- They need to be zonked, so we return them
704 traceTc (text "Tc7") ;
705 (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
708 rules <- tcRules rule_decls ;
711 traceTc (text "Tc7a") ;
712 tcg_env <- getGblEnv ;
713 let { all_binds = tc_val_binds `unionBags`
714 inst_binds `unionBags`
717 -- Extend the GblEnv with the (as yet un-zonked)
718 -- bindings, rules, foreign decls
719 tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds,
720 tcg_rules = tcg_rules tcg_env ++ rules,
721 tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
722 return (tcg_env', tcl_env)
727 %************************************************************************
731 %************************************************************************
734 checkMain :: TcM TcGblEnv
735 -- If we are in module Main, check that 'main' is defined.
737 = do { ghc_mode <- getGhcMode ;
738 tcg_env <- getGblEnv ;
740 let { main_mod = mainModIs dflags ;
741 main_fn = case mainFunIs dflags of {
742 Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn)) ;
743 Nothing -> main_RDR_Unqual } } ;
745 check_main ghc_mode tcg_env main_mod main_fn
749 check_main ghc_mode tcg_env main_mod main_fn
751 = traceTc (text "checkMain not" <+> ppr main_mod <+> ppr mod) >>
755 = addErrCtxt mainCtxt $
756 do { mb_main <- lookupSrcOcc_maybe main_fn
757 -- Check that 'main' is in scope
758 -- It might be imported from another module!
760 Nothing -> do { traceTc (text "checkMain fail" <+> ppr main_mod <+> ppr main_fn)
764 { traceTc (text "checkMain found" <+> ppr main_mod <+> ppr main_fn)
765 ; let { rhs = nlHsApp (nlHsVar runMainIOName) (nlHsVar main_name) }
766 -- :Main.main :: IO () = runMainIO main
768 ; (main_expr, ty) <- setSrcSpan (srcLocSpan (getSrcLoc main_name)) $
771 -- The function that the RTS invokes is always :Main.main,
772 -- which we call root_main_id.
773 -- (Because GHC allows the user to have a module not called
774 -- Main as the main module, we can't rely on the main function
775 -- being called "Main.main". That's why root_main_id has a fixed
777 -- We also make root_main_id an implicit Id, by making main_name
778 -- its parent (hence (Just main_name)). That has the effect
779 -- of preventing its type and unfolding from getting out into
780 -- the interface file. Otherwise we can end up with two defns
781 -- for 'main' in the interface file!
783 ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
784 (mkVarOccFS FSLIT("main"))
785 (getSrcLoc main_name)
786 ; root_main_id = mkExportedLocalId root_main_name ty
787 ; main_bind = noLoc (VarBind root_main_id main_expr) }
789 ; return (tcg_env { tcg_binds = tcg_binds tcg_env
791 tcg_dus = tcg_dus tcg_env
792 `plusDU` usesOnly (unitFV main_name)
793 -- Record the use of 'main', so that we don't
794 -- complain about it being defined but not used
798 mod = tcg_mod tcg_env
800 complain_no_main | ghc_mode == Interactive = return ()
801 | otherwise = failWithTc noMainMsg
802 -- In interactive mode, don't worry about the absence of 'main'
803 -- In other modes, fail altogether, so that we don't go on
804 -- and complain a second time when processing the export list.
806 mainCtxt = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
807 noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn)
808 <+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
811 %*********************************************************
815 %*********************************************************
819 setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
820 setInteractiveContext hsc_env icxt thing_inside
822 -- Initialise the tcg_inst_env with instances
823 -- from all home modules. This mimics the more selective
824 -- call to hptInstances in tcRnModule
825 dfuns = hptInstances hsc_env (\mod -> True)
827 updGblEnv (\env -> env {
828 tcg_rdr_env = ic_rn_gbl_env icxt,
829 tcg_type_env = ic_type_env icxt,
830 tcg_inst_env = extendInstEnvList (tcg_inst_env env) dfuns }) $
832 updLclEnv (\env -> env { tcl_rdr = ic_rn_local_env icxt }) $
834 do { traceTc (text "setIC" <+> ppr (ic_type_env icxt))
841 -> InteractiveContext
843 -> IO (Maybe (InteractiveContext, [Name], LHsExpr Id))
844 -- The returned [Name] is the same as the input except for
845 -- ExprStmt, in which case the returned [Name] is [itName]
847 -- The returned TypecheckedHsExpr is of type IO [ () ],
848 -- a list of the bound values, coerced to ().
850 tcRnStmt hsc_env ictxt rdr_stmt
851 = initTcPrintErrors hsc_env iNTERACTIVE $
852 setInteractiveContext hsc_env ictxt $ do {
854 -- Rename; use CmdLineMode because tcRnStmt is only used interactively
855 (([rn_stmt], _), fvs) <- rnStmts DoExpr [rdr_stmt] (return ((), emptyFVs)) ;
856 traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
859 -- The real work is done here
860 (bound_ids, tc_expr) <- mkPlan rn_stmt ;
861 zonked_expr <- zonkTopLExpr tc_expr ;
862 zonked_ids <- zonkTopBndrs bound_ids ;
864 -- None of the Ids should be of unboxed type, because we
865 -- cast them all to HValues in the end!
866 mappM bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
868 traceTc (text "tcs 1") ;
869 let { -- (a) Make all the bound ids "global" ids, now that
870 -- they're notionally top-level bindings. This is
871 -- important: otherwise when we come to compile an expression
872 -- using these ids later, the byte code generator will consider
873 -- the occurrences to be free rather than global.
875 -- (b) Tidy their types; this is important, because :info may
876 -- ask to look at them, and :info expects the things it looks
877 -- up to have tidy types
878 global_ids = map globaliseAndTidy zonked_ids ;
880 -- Update the interactive context
881 rn_env = ic_rn_local_env ictxt ;
882 type_env = ic_type_env ictxt ;
884 bound_names = map idName global_ids ;
885 new_rn_env = extendLocalRdrEnv rn_env bound_names ;
887 {- ---------------------------------------------
888 At one stage I removed any shadowed bindings from the type_env;
889 they are inaccessible but might, I suppose, cause a space leak if we leave them there.
890 However, with Template Haskell they aren't necessarily inaccessible. Consider this
892 Prelude> let f n = n * 2 :: Int
893 Prelude> fName <- runQ [| f |]
894 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
896 Prelude> let f n = n * 3 :: Int
897 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
898 In the last line we use 'fName', which resolves to the *first* 'f'
899 in scope. If we delete it from the type env, GHCi crashes because
900 it doesn't expect that.
902 Hence this code is commented out
904 shadowed = [ n | name <- bound_names,
905 let rdr_name = mkRdrUnqual (nameOccName name),
906 Just n <- [lookupLocalRdrEnv rn_env rdr_name] ] ;
907 filtered_type_env = delListFromNameEnv type_env shadowed ;
908 -------------------------------------------------- -}
910 new_type_env = extendTypeEnvWithIds type_env global_ids ;
911 new_ic = ictxt { ic_rn_local_env = new_rn_env,
912 ic_type_env = new_type_env }
915 dumpOptTcRn Opt_D_dump_tc
916 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
917 text "Typechecked expr" <+> ppr zonked_expr]) ;
919 returnM (new_ic, bound_names, zonked_expr)
922 bad_unboxed id = addErr (sep [ptext SLIT("GHCi can't bind a variable of unlifted type:"),
923 nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
925 globaliseAndTidy :: Id -> Id
927 -- Give the Id a Global Name, and tidy its type
928 = setIdType (globaliseId VanillaGlobal id) tidy_type
930 tidy_type = tidyTopType (idType id)
933 Here is the grand plan, implemented in tcUserStmt
935 What you type The IO [HValue] that hscStmt returns
936 ------------- ------------------------------------
937 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
940 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
943 expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
944 [NB: result not printed] bindings: [it]
946 expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
947 result showable) bindings: [it]
949 expr (of non-IO type,
950 result not showable) ==> error
954 ---------------------------
955 type PlanResult = ([Id], LHsExpr Id)
956 type Plan = TcM PlanResult
958 runPlans :: [Plan] -> TcM PlanResult
959 -- Try the plans in order. If one fails (by raising an exn), try the next.
960 -- If one succeeds, take it.
961 runPlans [] = panic "runPlans"
963 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
966 mkPlan :: LStmt Name -> TcM PlanResult
967 mkPlan (L loc (ExprStmt expr _ _)) -- An expression typed at the prompt
968 = do { uniq <- newUnique -- is treated very specially
969 ; let fresh_it = itName uniq
970 the_bind = L loc $ mkFunBind (L loc fresh_it) matches
971 matches = [mkMatch [] expr emptyLocalBinds]
972 let_stmt = L loc $ LetStmt (HsValBinds (ValBindsOut [(NonRecursive,unitBag the_bind)] []))
973 bind_stmt = L loc $ BindStmt (nlVarPat fresh_it) expr
974 (HsVar bindIOName) noSyntaxExpr
975 print_it = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar fresh_it))
976 (HsVar thenIOName) placeHolderType
979 -- [it <- e; print it] but not if it::()
981 -- [let it = e; print it]
982 ; runPlans [ -- Plan A
983 do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
984 ; it_ty <- zonkTcType (idType it_id)
985 ; ifM (isUnitTy it_ty) failM
988 -- Plan B; a naked bind statment
989 tcGhciStmts [bind_stmt],
991 -- Plan C; check that the let-binding is typeable all by itself.
992 -- If not, fail; if so, try to print it.
993 -- The two-step process avoids getting two errors: one from
994 -- the expression itself, and one from the 'print it' part
995 -- This two-step story is very clunky, alas
996 do { checkNoErrs (tcGhciStmts [let_stmt])
997 --- checkNoErrs defeats the error recovery of let-bindings
998 ; tcGhciStmts [let_stmt, print_it] }
1001 mkPlan stmt@(L loc (BindStmt {}))
1002 | [L _ v] <- collectLStmtBinders stmt -- One binder, for a bind stmt
1003 = do { let print_v = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
1004 (HsVar thenIOName) placeHolderType
1006 ; print_bind_result <- doptM Opt_PrintBindResult
1007 ; let print_plan = do
1008 { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
1009 ; v_ty <- zonkTcType (idType v_id)
1010 ; ifM (isUnitTy v_ty || not (isTauTy v_ty)) failM
1014 -- [stmt; print v] but not if v::()
1016 ; runPlans ((if print_bind_result then [print_plan] else []) ++
1017 [tcGhciStmts [stmt]])
1021 = tcGhciStmts [stmt]
1023 ---------------------------
1024 tcGhciStmts :: [LStmt Name] -> TcM PlanResult
1026 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
1027 ret_id <- tcLookupId returnIOName ; -- return @ IO
1029 io_ty = mkTyConApp ioTyCon [] ;
1030 ret_ty = mkListTy unitTy ;
1031 io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
1032 tc_io_stmts stmts = tcStmts DoExpr (tcDoStmt io_ty) stmts
1033 (emptyRefinement, io_ret_ty) ;
1035 names = map unLoc (collectLStmtsBinders stmts) ;
1037 -- mk_return builds the expression
1038 -- returnIO @ [()] [coerce () x, .., coerce () z]
1040 -- Despite the inconvenience of building the type applications etc,
1041 -- this *has* to be done in type-annotated post-typecheck form
1042 -- because we are going to return a list of *polymorphic* values
1043 -- coerced to type (). If we built a *source* stmt
1044 -- return [coerce x, ..., coerce z]
1045 -- then the type checker would instantiate x..z, and we wouldn't
1046 -- get their *polymorphic* values. (And we'd get ambiguity errs
1047 -- if they were overloaded, since they aren't applied to anything.)
1048 mk_return ids = nlHsApp (nlHsTyApp ret_id [ret_ty])
1049 (noLoc $ ExplicitList unitTy (map mk_item ids)) ;
1050 mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
1054 -- OK, we're ready to typecheck the stmts
1055 traceTc (text "tcs 2") ;
1056 ((tc_stmts, ids), lie) <- getLIE $ tc_io_stmts stmts $ \ _ ->
1057 mappM tcLookupId names ;
1058 -- Look up the names right in the middle,
1059 -- where they will all be in scope
1061 -- Simplify the context
1062 const_binds <- checkNoErrs (tcSimplifyInteractive lie) ;
1063 -- checkNoErrs ensures that the plan fails if context redn fails
1065 return (ids, mkHsDictLet const_binds $
1066 noLoc (HsDo DoExpr tc_stmts (mk_return ids) io_ret_ty))
1071 tcRnExpr just finds the type of an expression
1075 -> InteractiveContext
1078 tcRnExpr hsc_env ictxt rdr_expr
1079 = initTcPrintErrors hsc_env iNTERACTIVE $
1080 setInteractiveContext hsc_env ictxt $ do {
1082 (rn_expr, fvs) <- rnLExpr rdr_expr ;
1085 -- Now typecheck the expression;
1086 -- it might have a rank-2 type (e.g. :t runST)
1087 ((tc_expr, res_ty), lie) <- getLIE (tcInferRho rn_expr) ;
1088 ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie) ;
1089 tcSimplifyInteractive lie_top ;
1090 qtvs' <- mappM zonkQuantifiedTyVar qtvs ;
1092 let { all_expr_ty = mkForAllTys qtvs' $
1093 mkFunTys (map idType dict_ids) $
1095 zonkTcType all_expr_ty
1098 smpl_doc = ptext SLIT("main expression")
1101 tcRnType just finds the kind of a type
1105 -> InteractiveContext
1108 tcRnType hsc_env ictxt rdr_type
1109 = initTcPrintErrors hsc_env iNTERACTIVE $
1110 setInteractiveContext hsc_env ictxt $ do {
1112 rn_type <- rnLHsType doc rdr_type ;
1115 -- Now kind-check the type
1116 (ty', kind) <- kcHsType rn_type ;
1120 doc = ptext SLIT("In GHCi input")
1126 %************************************************************************
1128 More GHCi stuff, to do with browsing and getting info
1130 %************************************************************************
1134 -- ASSUMES that the module is either in the HomePackageTable or is
1135 -- a package module with an interface on disk. If neither of these is
1136 -- true, then the result will be an error indicating the interface
1137 -- could not be found.
1138 getModuleExports :: HscEnv -> Module -> IO (Messages, Maybe NameSet)
1139 getModuleExports hsc_env mod
1140 = initTc hsc_env HsSrcFile iNTERACTIVE (tcGetModuleExports mod)
1142 tcGetModuleExports :: Module -> TcM NameSet
1143 tcGetModuleExports mod = do
1144 let doc = ptext SLIT("context for compiling statements")
1145 iface <- initIfaceTcRn $ loadSysInterface doc mod
1146 loadOrphanModules (dep_orphs (mi_deps iface))
1147 -- Load any orphan-module interfaces,
1148 -- so their instances are visible
1149 ifaceExportNames (mi_exports iface)
1151 tcRnLookupRdrName :: HscEnv -> RdrName -> IO (Maybe [Name])
1152 tcRnLookupRdrName hsc_env rdr_name
1153 = initTcPrintErrors hsc_env iNTERACTIVE $
1154 setInteractiveContext hsc_env (hsc_IC hsc_env) $
1155 lookup_rdr_name rdr_name
1157 lookup_rdr_name rdr_name = do {
1158 -- If the identifier is a constructor (begins with an
1159 -- upper-case letter), then we need to consider both
1160 -- constructor and type class identifiers.
1161 let { rdr_names = dataTcOccs rdr_name } ;
1163 -- results :: [Either Messages Name]
1164 results <- mapM (tryTcErrs . lookupOccRn) rdr_names ;
1166 traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)]);
1167 -- The successful lookups will be (Just name)
1168 let { (warns_s, good_names) = unzip [ (msgs, name)
1169 | (msgs, Just name) <- results] ;
1170 errs_s = [msgs | (msgs, Nothing) <- results] } ;
1172 -- Fail if nothing good happened, else add warnings
1173 if null good_names then
1174 -- No lookup succeeded, so
1175 -- pick the first error message and report it
1176 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
1177 -- while the other is "X is not in scope",
1178 -- we definitely want the former; but we might pick the latter
1179 do { addMessages (head errs_s) ; failM }
1180 else -- Add deprecation warnings
1181 mapM_ addMessages warns_s ;
1187 tcRnLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
1188 tcRnLookupName hsc_env name
1189 = initTcPrintErrors hsc_env iNTERACTIVE $
1190 setInteractiveContext hsc_env (hsc_IC hsc_env) $
1194 tcRnGetInfo :: HscEnv
1196 -> IO (Maybe (TyThing, Fixity, [Instance]))
1198 -- Used to implemnent :info in GHCi
1200 -- Look up a RdrName and return all the TyThings it might be
1201 -- A capitalised RdrName is given to us in the DataName namespace,
1202 -- but we want to treat it as *both* a data constructor
1203 -- *and* as a type or class constructor;
1204 -- hence the call to dataTcOccs, and we return up to two results
1205 tcRnGetInfo hsc_env name
1206 = initTcPrintErrors hsc_env iNTERACTIVE $
1207 let ictxt = hsc_IC hsc_env in
1208 setInteractiveContext hsc_env ictxt $ do
1210 -- Load the interface for all unqualified types and classes
1211 -- That way we will find all the instance declarations
1212 -- (Packages have not orphan modules, and we assume that
1213 -- in the home package all relevant modules are loaded.)
1214 loadUnqualIfaces ictxt
1216 thing <- tcLookupGlobal name
1217 fixity <- lookupFixityRn name
1218 ispecs <- lookupInsts (icPrintUnqual ictxt) thing
1219 return (thing, fixity, ispecs)
1222 lookupInsts :: PrintUnqualified -> TyThing -> TcM [Instance]
1223 -- Filter the instances by the ones whose tycons (or clases resp)
1224 -- are in scope unqualified. Otherwise we list a whole lot too many!
1225 lookupInsts print_unqual (AClass cls)
1226 = do { inst_envs <- tcGetInstEnvs
1228 | ispec <- classInstances inst_envs cls
1229 , plausibleDFun print_unqual (instanceDFunId ispec) ] }
1231 lookupInsts print_unqual (ATyCon tc)
1232 = do { eps <- getEps -- Load all instances for all classes that are
1233 -- in the type environment (which are all the ones
1234 -- we've seen in any interface file so far)
1235 ; (pkg_ie, home_ie) <- tcGetInstEnvs -- Search all
1237 | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
1238 , let dfun = instanceDFunId ispec
1240 , plausibleDFun print_unqual dfun ] }
1242 relevant df = tc_name `elemNameSet` tyClsNamesOfDFunHead (idType df)
1243 tc_name = tyConName tc
1245 lookupInsts print_unqual other = return []
1247 plausibleDFun print_unqual dfun -- Dfun involving only names that print unqualified
1248 = all ok (nameSetToList (tyClsNamesOfType (idType dfun)))
1250 ok name | isBuiltInSyntax name = True
1251 | isExternalName name =
1252 isNothing $ fst print_unqual (nameModule name)
1256 loadUnqualIfaces :: InteractiveContext -> TcM ()
1257 -- Load the home module for everything that is in scope unqualified
1258 -- This is so that we can accurately report the instances for
1260 loadUnqualIfaces ictxt
1262 mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
1264 unqual_mods = [ nameModule name
1265 | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt),
1266 let name = gre_name gre,
1267 not (isInternalName name),
1268 isTcOcc (nameOccName name), -- Types and classes only
1269 unQualOK gre ] -- In scope unqualified
1270 doc = ptext SLIT("Need interface for module whose export(s) are in scope unqualified")
1274 %************************************************************************
1278 %************************************************************************
1281 rnDump :: SDoc -> TcRn ()
1282 -- Dump, with a banner, if -ddump-rn
1283 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
1285 tcDump :: TcGblEnv -> TcRn ()
1287 = do { dflags <- getDOpts ;
1289 -- Dump short output if -ddump-types or -ddump-tc
1290 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1291 (dumpTcRn short_dump) ;
1293 -- Dump bindings if -ddump-tc
1294 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1297 short_dump = pprTcGblEnv env
1298 full_dump = pprLHsBinds (tcg_binds env)
1299 -- NB: foreign x-d's have undefined's in their types;
1300 -- hence can't show the tc_fords
1303 = do { dflags <- getDOpts ;
1304 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1305 (dumpTcRn (pprModGuts mod_guts)) ;
1307 -- Dump bindings if -ddump-tc
1308 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1310 full_dump = pprCoreBindings (mg_binds mod_guts)
1312 -- It's unpleasant having both pprModGuts and pprModDetails here
1313 pprTcGblEnv :: TcGblEnv -> SDoc
1314 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
1316 tcg_fam_insts = fam_insts,
1318 tcg_imports = imports })
1319 = vcat [ ppr_types insts type_env
1321 , ppr_fam_insts fam_insts
1322 , vcat (map ppr rules)
1323 , ppr_gen_tycons (typeEnvTyCons type_env)
1324 , ptext SLIT("Dependent modules:") <+> ppr (eltsUFM (imp_dep_mods imports))
1325 , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1327 pprModGuts :: ModGuts -> SDoc
1328 pprModGuts (ModGuts { mg_types = type_env,
1330 = vcat [ ppr_types [] type_env,
1333 ppr_types :: [Instance] -> TypeEnv -> SDoc
1334 ppr_types insts type_env
1335 = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1337 dfun_ids = map instanceDFunId insts
1338 ids = [id | id <- typeEnvIds type_env, want_sig id]
1339 want_sig id | opt_PprStyle_Debug = True
1340 | otherwise = isLocalId id &&
1341 isExternalName (idName id) &&
1342 not (id `elem` dfun_ids)
1343 -- isLocalId ignores data constructors, records selectors etc.
1344 -- The isExternalName ignores local dictionary and method bindings
1345 -- that the type checker has invented. Top-level user-defined things
1346 -- have External names.
1348 ppr_insts :: [Instance] -> SDoc
1349 ppr_insts [] = empty
1350 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
1352 ppr_fam_insts :: [FamInst] -> SDoc
1353 ppr_fam_insts [] = empty
1354 ppr_fam_insts fam_insts =
1355 text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
1357 ppr_sigs :: [Var] -> SDoc
1359 -- Print type signatures; sort by OccName
1360 = vcat (map ppr_sig (sortLe le_sig ids))
1362 le_sig id1 id2 = getOccName id1 <= getOccName id2
1363 ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1365 ppr_rules :: [CoreRule] -> SDoc
1366 ppr_rules [] = empty
1367 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1368 nest 4 (pprRules rs),
1371 ppr_gen_tycons [] = empty
1372 ppr_gen_tycons tcs = vcat [ptext SLIT("Tycons with generics:"),
1373 nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]