[project @ 2002-10-09 15:51:43 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcRnDriver.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcModule]{Typechecking a whole module}
5
6 \begin{code}
7 module TcRnDriver (
8 #ifdef GHCI
9         mkGlobalContext, getModuleContents,
10 #endif
11         tcRnModule, checkOldIface, 
12         importSupportingDecls, tcTopSrcDecls,
13         tcRnIface, tcRnExtCore, tcRnStmt, tcRnExpr, tcRnThing
14     ) where
15
16 #include "HsVersions.h"
17
18 #ifdef GHCI
19 import {-# SOURCE #-} TcSplice( tcSpliceDecls )
20 #endif
21
22 import CmdLineOpts      ( DynFlag(..), opt_PprStyle_Debug, dopt )
23 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsDecl(..), HsExpr(..),
24                           Stmt(..), Pat(VarPat), HsStmtContext(..), RuleDecl(..),
25                           HsGroup(..),
26                           mkSimpleMatch, placeHolderType, toHsType, andMonoBinds,
27                           isSrcRule, collectStmtsBinders
28                         )
29 import RdrHsSyn         ( RdrNameHsModule, RdrNameHsDecl, RdrNameStmt, RdrNameHsExpr,
30                           emptyGroup, mkGroup, findSplice, addImpDecls )
31
32 import PrelNames        ( iNTERACTIVE, ioTyConName, printName,
33                           returnIOName, bindIOName, failIOName, thenIOName, runIOName, 
34                           dollarMainName, itName, mAIN_Name
35                         )
36 import MkId             ( unsafeCoerceId )
37 import RdrName          ( RdrName, getRdrName, mkUnqual, mkRdrUnqual, 
38                           lookupRdrEnv, elemRdrEnv )
39
40 import RnHsSyn          ( RenamedHsDecl, RenamedStmt, RenamedTyClDecl, 
41                           ruleDeclFVs, instDeclFVs, tyClDeclFVs )
42 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedRuleDecl,
43                           zonkTopBinds, zonkTopDecls, mkHsLet,
44                           zonkTopExpr, zonkTopBndrs
45                         )
46
47 import TcExpr           ( tcExpr_id )
48 import TcRnMonad
49 import TcMType          ( newTyVarTy, zonkTcType )
50 import TcType           ( Type, liftedTypeKind, 
51                           tyVarsOfType, tcFunResultTy,
52                           mkForAllTys, mkFunTys, mkTyConApp, tcSplitForAllTys
53                         )
54 import TcMatches        ( tcStmtsAndThen )
55 import Inst             ( showLIE )
56 import TcBinds          ( tcTopBinds )
57 import TcClassDcl       ( tcClassDecls2 )
58 import TcDefaults       ( tcDefaults )
59 import TcEnv            ( RecTcGblEnv, 
60                           tcExtendGlobalValEnv, 
61                           tcExtendGlobalEnv,
62                           tcExtendInstEnv, tcExtendRules,
63                           tcLookupTyCon, tcLookupGlobal,
64                           tcLookupId 
65                         )
66 import TcRules          ( tcRules )
67 import TcForeign        ( tcForeignImports, tcForeignExports )
68 import TcIfaceSig       ( tcInterfaceSigs, tcCoreBinds )
69 import TcInstDcls       ( tcInstDecls1, tcIfaceInstDecls, tcInstDecls2 )
70 import TcSimplify       ( tcSimplifyTop, tcSimplifyInfer )
71 import TcTyClsDecls     ( tcTyAndClassDecls )
72
73 import RnNames          ( rnImports, exportsFromAvail, reportUnusedNames )
74 import RnIfaces         ( slurpImpDecls, checkVersions, RecompileRequired, outOfDate )
75 import RnHiFiles        ( readIface, loadOldIface )
76 import RnEnv            ( lookupSrcName, lookupOccRn, plusGlobalRdrEnv,
77                           ubiquitousNames, implicitModuleFVs, implicitStmtFVs, dataTcOccs )
78 import RnExpr           ( rnStmts, rnExpr )
79 import RnNames          ( importsFromLocalDecls )
80 import RnSource         ( rnSrcDecls, checkModDeprec, rnStats )
81
82 import OccName          ( varName )
83 import CoreUnfold       ( unfoldingTemplate )
84 import CoreSyn          ( IdCoreRule, Bind(..) )
85 import PprCore          ( pprIdRules, pprCoreBindings )
86 import TysWiredIn       ( mkListTy, unitTy )
87 import ErrUtils         ( mkDumpDoc, showPass )
88 import Id               ( Id, mkLocalId, isLocalId, idName, idType, idUnfolding, setIdLocalExported )
89 import IdInfo           ( GlobalIdDetails(..) )
90 import Var              ( Var, setGlobalIdDetails )
91 import Module           ( Module, moduleName, moduleUserString )
92 import Name             ( Name, isExternalName, getSrcLoc, nameOccName )
93 import NameEnv          ( delListFromNameEnv )
94 import NameSet
95 import TyCon            ( tyConGenInfo )
96 import BasicTypes       ( EP(..), RecFlag(..) )
97 import SrcLoc           ( noSrcLoc )
98 import Outputable
99 import HscTypes         ( PersistentCompilerState(..), InteractiveContext(..),
100                           ModIface, ModDetails(..), ModGuts(..),
101                           HscEnv(..), 
102                           ModIface(..), ModDetails(..), IfaceDecls(..),
103                           GhciMode(..), 
104                           Deprecations(..), plusDeprecs,
105                           emptyGlobalRdrEnv,
106                           GenAvailInfo(Avail), availsToNameSet, 
107                           ForeignStubs(..),
108                           TypeEnv, TyThing, typeEnvTyCons, 
109                           extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
110                           extendLocalRdrEnv, emptyFixityEnv
111                         )
112 #ifdef GHCI
113 import RdrName          ( rdrEnvElts )
114 import RnHiFiles        ( loadInterface )
115 import RnEnv            ( mkGlobalRdrEnv )
116 import HscTypes         ( GlobalRdrElt(..), GlobalRdrEnv, ImportReason(..), Provenance(..), 
117                           isLocalGRE )
118 #endif
119
120 import Maybe            ( catMaybes )
121 import Panic            ( showException )
122 import List             ( partition )
123 import Util             ( sortLt )
124 \end{code}
125
126
127
128 %************************************************************************
129 %*                                                                      *
130         Typecheck and rename a module
131 %*                                                                      *
132 %************************************************************************
133
134
135 \begin{code}
136 tcRnModule :: HscEnv -> PersistentCompilerState
137            -> RdrNameHsModule 
138            -> IO (PersistentCompilerState, Maybe TcGblEnv)
139
140 tcRnModule hsc_env pcs
141            (HsModule this_mod _ exports import_decls local_decls mod_deprec loc)
142  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
143
144    initTc hsc_env pcs this_mod $ addSrcLoc loc $
145    do {         -- Deal with imports; sets tcg_rdr_env, tcg_imports
146         (rdr_env, imports) <- rnImports import_decls ;
147         updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
148                                    tcg_imports = imports }) 
149                      $ do {
150         traceRn (text "rn1") ;
151                 -- Fail if there are any errors so far
152                 -- The error printing (if needed) takes advantage 
153                 -- of the tcg_env we have now set
154         failIfErrsM ;
155
156         traceRn (text "rn1a") ;
157                 -- Rename and type check the declarations
158         (tcg_env, src_fvs) <- tcRnSrcDecls local_decls ;
159         setGblEnv tcg_env               $ do {
160         traceRn (text "rn2") ;
161
162                 -- Check for 'main'
163         (tcg_env, main_fvs) <- checkMain ;
164         setGblEnv tcg_env               $ do {
165
166         traceRn (text "rn3") ;
167                 -- Check whether the entire module is deprecated
168                 -- This happens only once per module
169                 -- Returns the full new deprecations; a module deprecation 
170                 --      over-rides the earlier ones
171         let { mod_deprecs = checkModDeprec mod_deprec } ;
172         updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` mod_deprecs })
173                   $ do {
174
175         traceRn (text "rn4") ;
176                 -- Process the export list
177         export_avails <- exportsFromAvail exports ;
178         updGblEnv (\gbl -> gbl { tcg_exports = export_avails })
179                   $  do {
180
181                 -- Get the supporting decls for the exports
182                 -- This is important *only* to gether usage information
183                 --      (see comments with MkIface.mkImportInfo for why)
184                 -- For OneShot compilation we could just throw away the decls
185                 -- but for Batch or Interactive we must put them in the type
186                 -- envt because they've been removed from the holding pen
187         let { export_fvs = availsToNameSet export_avails } ;
188         tcg_env <- importSupportingDecls export_fvs ;
189         setGblEnv tcg_env $ do {
190
191                 -- Report unused names
192         let { used_fvs = src_fvs `plusFV` main_fvs `plusFV` export_fvs } ;
193         reportUnusedNames tcg_env used_fvs ;
194
195                 -- Dump output and return
196         tcDump tcg_env ;
197         return tcg_env
198     }}}}}}}}
199 \end{code}
200
201
202 %*********************************************************
203 %*                                                       *
204 \subsection{Closing up the interface decls}
205 %*                                                       *
206 %*********************************************************
207
208 Suppose we discover we don't need to recompile.   Then we start from the
209 IfaceDecls in the ModIface, and fluff them up by sucking in all the decls they need.
210
211 \begin{code}
212 tcRnIface :: HscEnv
213           -> PersistentCompilerState
214           -> ModIface   -- Get the decls from here
215           -> IO (PersistentCompilerState, Maybe ModDetails)
216                                 -- Nothing <=> errors happened
217 tcRnIface hsc_env pcs
218             (ModIface {mi_module = mod, mi_decls = iface_decls})
219   = initTc hsc_env pcs mod $ do {
220
221         -- Get the supporting decls, and typecheck them all together
222         -- so that any mutually recursive types are done right
223     extra_decls <- slurpImpDecls needed ;
224     env <- typecheckIfaceDecls (group `addImpDecls` extra_decls) ;
225
226     returnM (ModDetails { md_types = tcg_type_env env,
227                           md_insts = tcg_insts env,
228                           md_rules = hsCoreRules (tcg_rules env)
229                   -- All the rules from an interface are of the IfaceRuleOut form
230                  }) }
231   where
232         rule_decls = dcl_rules iface_decls
233         inst_decls = dcl_insts iface_decls
234         tycl_decls = dcl_tycl  iface_decls
235         group = emptyGroup { hs_ruleds = rule_decls,
236                              hs_instds = inst_decls,
237                              hs_tyclds = tycl_decls }
238         needed = unionManyNameSets (map ruleDeclFVs rule_decls) `unionNameSets`
239                  unionManyNameSets (map instDeclFVs inst_decls) `unionNameSets`
240                  unionManyNameSets (map tyClDeclFVs tycl_decls) `unionNameSets`
241                  ubiquitousNames
242                         -- Data type decls with record selectors,
243                         -- which may appear in the decls, need unpackCString
244                         -- and friends. It's easier to just grab them right now.
245
246 hsCoreRules :: [TypecheckedRuleDecl] -> [IdCoreRule]
247 -- All post-typechecking Iface rules have the form IfaceRuleOut
248 hsCoreRules rules = [(id,rule) | IfaceRuleOut id rule <- rules]
249 \end{code}
250
251
252 %************************************************************************
253 %*                                                                      *
254                 The interactive interface 
255 %*                                                                      *
256 %************************************************************************
257
258 \begin{code}
259 tcRnStmt :: HscEnv -> PersistentCompilerState
260          -> InteractiveContext
261          -> RdrNameStmt
262          -> IO (PersistentCompilerState, 
263                 Maybe (InteractiveContext, [Name], TypecheckedHsExpr))
264                 -- The returned [Id] is the same as the input except for
265                 -- ExprStmt, in which case the returned [Name] is [itName]
266
267 tcRnStmt hsc_env pcs ictxt rdr_stmt
268   = initTc hsc_env pcs iNTERACTIVE $ 
269     setInteractiveContext ictxt $ do {
270
271     -- Rename; use CmdLineMode because tcRnStmt is only used interactively
272     ([rn_stmt], fvs) <- initRnInteractive ictxt 
273                                         (rnStmts DoExpr [rdr_stmt]) ;
274     traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
275     failIfErrsM ;
276     
277     -- Suck in the supporting declarations and typecheck them
278     tcg_env <- importSupportingDecls (fvs `plusFV` implicitStmtFVs fvs) ;
279         -- NB: an earlier version deleted (rdrEnvElts local_env) from
280         --     the fvs.  But (a) that isn't necessary, because previously
281         --     bound things in the local_env will be in the TypeEnv, and 
282         --     the renamer doesn't re-slurp such things, and 
283         -- (b) it's WRONG to delete them. Consider in GHCi:
284         --        Mod> let x = e :: T
285         --        Mod> let y = x + 3
286         --     We need to pass 'x' among the fvs to slurpImpDecls, so that
287         --     the latter can see that T is a gate, and hence import the Num T 
288         --     instance decl.  (See the InTypEnv case in RnIfaces.slurpSourceRefs.)
289     setGblEnv tcg_env $ do {
290     
291     -- The real work is done here
292     ((bound_ids, tc_expr), lie) <- getLIE (tcUserStmt rn_stmt) ;
293     
294     traceTc (text "tcs 1") ;
295     let {       -- Make all the bound ids "global" ids, now that
296                 -- they're notionally top-level bindings.  This is
297                 -- important: otherwise when we come to compile an expression
298                 -- using these ids later, the byte code generator will consider
299                 -- the occurrences to be free rather than global.
300         global_ids     = map globaliseId bound_ids ;
301         globaliseId id = setGlobalIdDetails id VanillaGlobal ;
302     
303                 -- Update the interactive context
304         rn_env   = ic_rn_local_env ictxt ;
305         type_env = ic_type_env ictxt ;
306
307         bound_names = map idName global_ids ;
308         new_rn_env  = extendLocalRdrEnv rn_env bound_names ;
309
310                 -- Remove any shadowed bindings from the type_env;
311                 -- they are inaccessible but might, I suppose, cause 
312                 -- a space leak if we leave them there
313         shadowed = [ n | name <- bound_names,
314                          let rdr_name = mkRdrUnqual (nameOccName name),
315                          Just n <- [lookupRdrEnv rn_env rdr_name] ] ;
316
317         filtered_type_env = delListFromNameEnv type_env shadowed ;
318         new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;
319
320         new_ic = ictxt { ic_rn_local_env = new_rn_env, 
321                          ic_type_env     = new_type_env }
322     } ;
323
324     dumpOptTcRn Opt_D_dump_tc 
325         (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
326                text "Typechecked expr" <+> ppr tc_expr]) ;
327
328     returnM (new_ic, bound_names, tc_expr)
329     }}
330 \end{code}              
331
332
333 Here is the grand plan, implemented in tcUserStmt
334
335         What you type                   The IO [HValue] that hscStmt returns
336         -------------                   ------------------------------------
337         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
338                                         bindings: [x,y,...]
339
340         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
341                                         bindings: [x,y,...]
342
343         expr (of IO type)       ==>     expr >>= \ v -> return [coerce HVal v]
344           [NB: result not printed]      bindings: [it]
345           
346         expr (of non-IO type,   ==>     let v = expr in print v >> return [coerce HVal v]
347           result showable)              bindings: [it]
348
349         expr (of non-IO type, 
350           result not showable)  ==>     error
351
352
353 \begin{code}
354 ---------------------------
355 tcUserStmt :: RenamedStmt -> TcM ([Id], TypecheckedHsExpr)
356 tcUserStmt (ExprStmt expr _ loc)
357   = newUnique           `thenM` \ uniq ->
358     let 
359         fresh_it = itName uniq
360         the_bind = FunMonoBind fresh_it False 
361                         [ mkSimpleMatch [] expr placeHolderType loc ] loc
362     in
363     tryTcLIE_ (do {     -- Try this if the other fails
364                 traceTc (text "tcs 1b") ;
365                 tc_stmts [
366                     LetStmt (MonoBind the_bind [] NonRecursive),
367                     ExprStmt (HsApp (HsVar printName) (HsVar fresh_it)) 
368                              placeHolderType loc] })
369           (do {         -- Try this first 
370                 traceTc (text "tcs 1a") ;
371                 tc_stmts [BindStmt (VarPat fresh_it) expr loc] })
372
373 tcUserStmt stmt = tc_stmts [stmt]
374
375 ---------------------------
376 tc_stmts stmts
377  = do { io_ids <- mappM tcLookupId 
378                         [returnIOName, failIOName, bindIOName, thenIOName] ;
379         ioTyCon <- tcLookupTyCon ioTyConName ;
380         res_ty  <- newTyVarTy liftedTypeKind ;
381         let {
382             names      = collectStmtsBinders stmts ;
383             return_id  = head io_ids ;  -- Rather gruesome
384
385             io_ty = (\ ty -> mkTyConApp ioTyCon [ty], res_ty) ;
386
387                 -- mk_return builds the expression
388                 --      returnIO @ [()] [coerce () x, ..,  coerce () z]
389             mk_return ids = HsApp (TyApp (HsVar return_id) [mkListTy unitTy]) 
390                                   (ExplicitList unitTy (map mk_item ids)) ;
391
392             mk_item id = HsApp (TyApp (HsVar unsafeCoerceId) [idType id, unitTy])
393                                (HsVar id) } ;
394
395         -- OK, we're ready to typecheck the stmts
396         traceTc (text "tcs 2") ;
397         ((ids, tc_stmts), lie) <- 
398                 getLIE $ tcStmtsAndThen combine DoExpr io_ty stmts $ 
399                 do {
400                     -- Look up the names right in the middle,
401                     -- where they will all be in scope
402                     ids <- mappM tcLookupId names ;
403                     return (ids, [ResultStmt (mk_return ids) noSrcLoc])
404                 } ;
405
406         -- Simplify the context right here, so that we fail
407         -- if there aren't enough instances.  Notably, when we see
408         --              e
409         -- we use recoverTc_ to try     it <- e
410         -- and then                     let it = e
411         -- It's the simplify step that rejects the first.
412         traceTc (text "tcs 3") ;
413         const_binds <- tcSimplifyTop lie ;
414
415         -- Build result expression and zonk it
416         let { expr = mkHsLet const_binds $
417                      HsDo DoExpr tc_stmts io_ids
418                           (mkTyConApp ioTyCon [mkListTy unitTy]) noSrcLoc } ;
419         zonked_expr <- zonkTopExpr expr ;
420         zonked_ids  <- zonkTopBndrs ids ;
421
422         return (zonked_ids, zonked_expr)
423         }
424   where
425     combine stmt (ids, stmts) = (ids, stmt:stmts)
426 \end{code}
427
428
429 tcRnExpr just finds the type of an expression
430
431 \begin{code}
432 tcRnExpr :: HscEnv -> PersistentCompilerState
433          -> InteractiveContext
434          -> RdrNameHsExpr
435          -> IO (PersistentCompilerState, Maybe Type)
436 tcRnExpr hsc_env pcs ictxt rdr_expr
437   = initTc hsc_env pcs iNTERACTIVE $ 
438     setInteractiveContext ictxt $ do {
439
440     (rn_expr, fvs) <- initRnInteractive ictxt (rnExpr rdr_expr) ;
441     failIfErrsM ;
442
443         -- Suck in the supporting declarations and typecheck them
444     tcg_env <- importSupportingDecls (fvs `plusFV` ubiquitousNames) ;
445     setGblEnv tcg_env $ do {
446     
447         -- Now typecheck the expression; 
448         -- it might have a rank-2 type (e.g. :t runST)
449         -- Hence the hole type (c.f. TcExpr.tcExpr_id)
450     ((tc_expr, res_ty), lie)       <- getLIE (tcExpr_id rn_expr) ;
451     ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie)  ;
452     tcSimplifyTop lie_top ;
453
454     let { all_expr_ty = mkForAllTys qtvs                $
455                         mkFunTys (map idType dict_ids)  $
456                         res_ty } ;
457     zonkTcType all_expr_ty
458     }}
459   where
460     smpl_doc = ptext SLIT("main expression")
461 \end{code}
462
463
464 \begin{code}
465 tcRnThing :: HscEnv -> PersistentCompilerState
466           -> InteractiveContext
467           -> RdrName
468           -> IO (PersistentCompilerState, Maybe [TyThing])
469 -- Look up a RdrName and return all the TyThings it might be
470 -- We treat a capitalised RdrName as both a data constructor 
471 -- and as a type or class constructor; hence we return up to two results
472 tcRnThing hsc_env pcs ictxt rdr_name
473   = initTc hsc_env pcs iNTERACTIVE $ 
474     setInteractiveContext ictxt $ do {
475
476         -- If the identifier is a constructor (begins with an
477         -- upper-case letter), then we need to consider both
478         -- constructor and type class identifiers.
479     let { rdr_names = dataTcOccs rdr_name } ;
480
481     (msgs_s, mb_names) <- initRnInteractive ictxt
482                             (mapAndUnzipM (tryTc . lookupOccRn) rdr_names) ;
483     let { names = catMaybes mb_names } ;
484
485     if null names then
486         do { addMessages (head msgs_s) ; failM }
487     else do {
488
489     mapM_ addMessages msgs_s ;  -- Add deprecation warnings
490     mapM tcLookupGlobal names   -- and lookup up the entities
491     }}
492 \end{code}
493
494
495 \begin{code}
496 setInteractiveContext :: InteractiveContext -> TcRn m a -> TcRn m a
497 setInteractiveContext icxt thing_inside 
498   = traceTc (text "setIC" <+> ppr (ic_type_env icxt))   `thenM_`
499     updGblEnv (\ env -> env { tcg_rdr_env  = ic_rn_gbl_env icxt,
500                               tcg_type_env = ic_type_env   icxt })
501               thing_inside
502
503 initRnInteractive :: InteractiveContext -> RnM a -> TcM a
504 -- Set the local RdrEnv from the interactive context
505 initRnInteractive ictxt rn_thing
506   = initRn CmdLineMode $
507     setLocalRdrEnv (ic_rn_local_env ictxt) $
508     rn_thing
509 \end{code}
510
511 %************************************************************************
512 %*                                                                      *
513         Type-checking external-core modules
514 %*                                                                      *
515 %************************************************************************
516
517 \begin{code}
518 tcRnExtCore :: HscEnv -> PersistentCompilerState 
519             -> RdrNameHsModule 
520             -> IO (PersistentCompilerState, Maybe ModGuts)
521         -- Nothing => some error occurred 
522
523 tcRnExtCore hsc_env pcs 
524             (HsModule this_mod _ _ _ local_decls _ loc)
525         -- Rename the (Core) module.  It's a bit like an interface
526         -- file: all names are original names
527  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
528
529    initTc hsc_env pcs this_mod $ addSrcLoc loc $ do {
530
531         -- Rename the source, only in interface mode.
532         -- rnSrcDecls handles fixity decls etc too, which won't occur
533         -- but that doesn't matter
534    let { local_group = mkGroup local_decls } ;
535    (_, rn_local_decls, fvs) <- initRn (InterfaceMode this_mod) 
536                                       (rnSrcDecls local_group) ;
537    failIfErrsM ;
538
539         -- Get the supporting decls, and typecheck them all together
540         -- so that any mutually recursive types are done right
541    extra_decls <- slurpImpDecls fvs ;
542    tcg_env <- typecheckIfaceDecls (rn_local_decls `addImpDecls` extra_decls) ;
543    setGblEnv tcg_env $ do {
544    
545         -- Now the core bindings
546    core_prs <- tcCoreBinds (hs_coreds rn_local_decls) ;
547    tcExtendGlobalValEnv (map fst core_prs) $ do {
548    
549         -- Wrap up
550    let {
551         bndrs      = map fst core_prs ;
552         my_exports = map (Avail . idName) bndrs ;
553                 -- ToDo: export the data types also?
554
555         final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
556
557         mod_guts = ModGuts {    mg_module   = this_mod,
558                                 mg_usages   = [],       -- ToDo: compute usage
559                                 mg_dir_imps = [],       -- ??
560                                 mg_exports  = my_exports,
561                                 mg_types    = final_type_env,
562                                 mg_insts    = tcg_insts tcg_env,
563                                 mg_rules    = hsCoreRules (tcg_rules tcg_env),
564                                 mg_binds    = [Rec core_prs],
565
566                                 -- Stubs
567                                 mg_rdr_env  = emptyGlobalRdrEnv,
568                                 mg_fix_env  = emptyFixityEnv,
569                                 mg_deprecs  = NoDeprecs,
570                                 mg_foreign  = NoStubs
571                     } } ;
572
573    tcCoreDump mod_guts ;
574
575    return mod_guts
576    }}}}
577 \end{code}
578
579
580 %************************************************************************
581 %*                                                                      *
582         Type-checking the top level of a module
583 %*                                                                      *
584 %************************************************************************
585
586 \begin{code}
587 tcRnSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, FreeVars)
588         -- Returns the variables free in the decls
589         -- Reason: solely to report unused imports and bindings
590 tcRnSrcDecls [] = do { tcg_env <- getGblEnv ; return (tcg_env, emptyFVs) }
591 tcRnSrcDecls ds
592  = do { let { (first_group, group_tail) = findSplice ds } ;
593
594         -- Type check the decls up to, but not including, the first splice
595         (tcg_env, src_fvs1) <- tcRnGroup first_group ;
596
597         -- If there is no splice, we're done
598         case group_tail of
599            Nothing -> return (tcg_env, src_fvs1)
600            Just (splice_expr, rest_ds) -> do {
601
602         setGblEnv tcg_env $ do {
603
604 #ifndef GHCI
605         failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
606 #else
607         -- Rename the splice expression, and get its supporting decls
608         (rn_splice_expr, fvs) <- initRn SourceMode (rnExpr splice_expr) ;
609         tcg_env <- importSupportingDecls fvs ;
610         setGblEnv tcg_env $ do {
611
612         -- Execute the splice
613         spliced_decls <- tcSpliceDecls rn_splice_expr ;
614
615         -- Glue them on the front of the remaining decls and loop
616         (tcg_env, src_fvs2) <- tcRnSrcDecls (spliced_decls ++ rest_ds) ;
617
618         return (tcg_env, src_fvs1 `plusFV` src_fvs2)
619     }
620 #endif /* GHCI */
621     }}}
622 \end{code}
623
624
625 %************************************************************************
626 %*                                                                      *
627         Type-checking the top level of a module
628 %*                                                                      *
629 %************************************************************************
630
631 tcRnGroup takes a bunch of top-level source-code declarations, and
632  * renames them
633  * gets supporting declarations from interface files
634  * typechecks them
635  * zonks them
636  * and augments the TcGblEnv with the results
637
638 In Template Haskell it may be called repeatedly for each group of
639 declarations.  It expects there to be an incoming TcGblEnv in the
640 monad; it augments it and returns the new TcGblEnv.
641
642 \begin{code}
643 tcRnGroup :: HsGroup RdrName -> TcM (TcGblEnv, FreeVars)
644         -- Returns the variables free in the decls
645 tcRnGroup decls
646  = do {         -- Rename the declarations
647         (tcg_env, rn_decls, src_fvs) <- rnTopSrcDecls decls ;
648         setGblEnv tcg_env $ do {
649
650                 -- Typecheck the declarations
651         tcg_env <- tcTopSrcDecls rn_decls ;
652         return (tcg_env, src_fvs)
653   }}
654
655 ------------------------------------------------
656 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name, FreeVars)
657 rnTopSrcDecls group
658  = do {         -- Bring top level binders into scope
659         (rdr_env, imports) <- importsFromLocalDecls group ;
660         updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv`
661                                                   tcg_rdr_env gbl,
662                                  tcg_imports = imports `plusImportAvails` 
663                                                   tcg_imports gbl }) 
664                      $ do {
665
666         failIfErrsM ;   -- No point in continuing if (say) we have duplicate declarations
667
668                 -- Rename the source decls
669         (tcg_env, rn_src_decls, src_fvs) <- initRn SourceMode (rnSrcDecls group) ;
670         setGblEnv tcg_env $ do {
671
672         failIfErrsM ;
673
674                 -- Import consquential imports
675         rn_imp_decls <- slurpImpDecls (src_fvs `plusFV` implicitModuleFVs src_fvs) ;
676         let { rn_decls = rn_src_decls `addImpDecls` rn_imp_decls } ;
677
678                 -- Dump trace of renaming part
679         rnDump (ppr rn_decls) ;
680         rnStats rn_imp_decls ;
681
682         return (tcg_env, rn_decls, src_fvs)
683   }}}
684
685 ------------------------------------------------
686 tcTopSrcDecls :: HsGroup Name -> TcM TcGblEnv
687 tcTopSrcDecls rn_decls
688  = fixM (\ unf_env -> do {      
689         -- Loop back the final environment, including the fully zonked
690         -- versions of bindings from this module.  In the presence of mutual
691         -- recursion, interface type signatures may mention variables defined
692         -- in this module, which is why the knot is so big
693
694                         -- Do the main work
695         ((tcg_env, binds, rules, fords), lie) <- getLIE (
696                 tc_src_decls unf_env rn_decls
697             ) ;
698
699              -- tcSimplifyTop deals with constant or ambiguous InstIds.  
700              -- How could there be ambiguous ones?  They can only arise if a
701              -- top-level decl falls under the monomorphism
702              -- restriction, and no subsequent decl instantiates its
703              -- type.  (Usually, ambiguous type variables are resolved
704              -- during the generalisation step.)
705         traceTc (text "Tc8") ;
706         inst_binds <- setGblEnv tcg_env (tcSimplifyTop lie) ;
707                 -- The setGblEnv exposes the instances to tcSimplifyTop
708
709             -- Backsubstitution.  This must be done last.
710             -- Even tcSimplifyTop may do some unification.
711         traceTc (text "Tc9") ;
712         (ids, binds', fords', rules') <- zonkTopDecls (binds `andMonoBinds` inst_binds)
713                                                       rules fords ;
714
715         let { tcg_env' = tcg_env { tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) ids,
716                                    tcg_binds = tcg_binds tcg_env `andMonoBinds` binds',
717                                    tcg_rules = tcg_rules tcg_env ++ rules',
718                                    tcg_fords = tcg_fords tcg_env ++ fords' } } ;
719         
720         return tcg_env' 
721     })
722
723 tc_src_decls unf_env 
724         (HsGroup { hs_tyclds = tycl_decls, 
725                    hs_instds = inst_decls,
726                    hs_fords  = foreign_decls,
727                    hs_defds  = default_decls,
728                    hs_ruleds = rule_decls,
729                    hs_valds  = val_binds })
730  = do {         -- Type-check the type and class decls, and all imported decls
731         traceTc (text "Tc2") ;
732         tcg_env <- tcTyClDecls unf_env tycl_decls ;
733         setGblEnv tcg_env       $ do {
734
735                 -- Source-language instances, including derivings,
736                 -- and import the supporting declarations
737         traceTc (text "Tc3") ;
738         (tcg_env, inst_infos, deriv_binds, fvs) <- tcInstDecls1 tycl_decls inst_decls ;
739         setGblEnv tcg_env       $ do {
740         tcg_env <- importSupportingDecls fvs ;
741         setGblEnv tcg_env       $ do {
742
743                 -- Foreign import declarations next.  No zonking necessary
744                 -- here; we can tuck them straight into the global environment.
745         traceTc (text "Tc4") ;
746         (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
747         tcExtendGlobalValEnv fi_ids                  $
748         updGblEnv (\gbl -> gbl { tcg_fords = tcg_fords gbl ++ fi_decls }) 
749                   $ do {
750
751                 -- Default declarations
752         traceTc (text "Tc4a") ;
753         default_tys <- tcDefaults default_decls ;
754         updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
755         
756                 -- Value declarations next
757                 -- We also typecheck any extra binds that came out 
758                 -- of the "deriving" process
759         traceTc (text "Tc5") ;
760         (tc_val_binds, lcl_env) <- tcTopBinds (val_binds `ThenBinds` deriv_binds) ;
761         setLclTypeEnv lcl_env   $ do {
762
763                 -- Second pass over class and instance declarations, 
764                 -- plus rules and foreign exports, to generate bindings
765         traceTc (text "Tc6") ;
766         (cls_dm_binds, dm_ids) <- tcClassDecls2 tycl_decls ;
767         tcExtendGlobalValEnv dm_ids     $ do {
768         inst_binds <- tcInstDecls2 inst_infos ;
769         showLIE "after instDecls2" ;
770
771                 -- Foreign exports
772                 -- They need to be zonked, so we return them
773         traceTc (text "Tc7") ;
774         (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
775
776                 -- Rules
777                 -- Need to partition them because the source rules
778                 -- must be zonked before adding them to tcg_rules
779                 -- NB: built-in rules come in as IfaceRuleOut's, and
780                 --     get added to tcg_rules right here by tcExtendRules
781         rules <- tcRules rule_decls ;
782         let { (src_rules, iface_rules) = partition isSrcRule rules } ;
783         tcExtendRules iface_rules $ do {
784
785                 -- Wrap up
786         tcg_env <- getGblEnv ;
787         let { all_binds = tc_val_binds   `AndMonoBinds`
788                           inst_binds     `AndMonoBinds`
789                           cls_dm_binds   `AndMonoBinds`
790                           foe_binds } ;
791
792         return (tcg_env, all_binds, src_rules, foe_decls)
793      }}}}}}}}}
794 \end{code}
795
796 \begin{code}
797 tcTyClDecls :: RecTcGblEnv
798             -> [RenamedTyClDecl]
799             -> TcM TcGblEnv
800
801 -- tcTyClDecls deals with 
802 --      type and class decls (some source, some imported)
803 --      interface signatures (checked lazily)
804 --
805 -- It returns the TcGblEnv for this module, and side-effects the
806 -- persistent compiler state to reflect the things imported from
807 -- other modules
808
809 tcTyClDecls unf_env tycl_decls
810   -- (unf_env :: RecTcGblEnv) is used for type-checking interface pragmas
811   -- which is done lazily [ie failure just drops the pragma
812   -- without having any global-failure effect].
813
814   = checkNoErrs $
815         -- tcTyAndClassDecls recovers internally, but if anything gave rise to
816         -- an error we'd better stop now, to avoid a cascade
817         
818     traceTc (text "TyCl1")              `thenM_`
819     tcTyAndClassDecls tycl_decls        `thenM` \ tycl_things ->
820     tcExtendGlobalEnv tycl_things       $
821     
822         -- Interface type signatures
823         -- We tie a knot so that the Ids read out of interfaces are in scope
824         --   when we read their pragmas.
825         -- What we rely on is that pragmas are typechecked lazily; if
826         --   any type errors are found (ie there's an inconsistency)
827         --   we silently discard the pragma
828     traceTc (text "TyCl2")                      `thenM_`
829     tcInterfaceSigs unf_env tycl_decls          `thenM` \ sig_ids ->
830     tcExtendGlobalValEnv sig_ids                $
831     
832     getGblEnv           -- Return the TcLocals environment
833 \end{code}    
834
835
836
837 %************************************************************************
838 %*                                                                      *
839         Load the old interface file for this module (unless
840         we have it aleady), and check whether it is up to date
841         
842 %*                                                                      *
843 %************************************************************************
844
845 \begin{code}
846 checkOldIface :: HscEnv
847               -> PersistentCompilerState
848               -> Module
849               -> FilePath               -- Where the interface file is
850               -> Bool                   -- Source unchanged
851               -> Maybe ModIface         -- Old interface from compilation manager, if any
852               -> IO (PersistentCompilerState, Maybe (RecompileRequired, Maybe ModIface))
853                                 -- Nothing <=> errors happened
854
855 checkOldIface hsc_env pcs mod iface_path source_unchanged maybe_iface
856   = do { showPass (hsc_dflags hsc_env) 
857                   ("Checking old interface for " ++ moduleUserString mod) ;
858
859          initTc hsc_env pcs mod
860                 (check_old_iface iface_path source_unchanged maybe_iface)
861      }
862
863 check_old_iface iface_path source_unchanged maybe_iface
864  =      -- CHECK WHETHER THE SOURCE HAS CHANGED
865     ifM (not source_unchanged)
866         (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
867                                                 `thenM_`
868
869      -- If the source has changed and we're in interactive mode, avoid reading
870      -- an interface; just return the one we might have been supplied with.
871     getGhciMode                                 `thenM` \ ghci_mode ->
872     if (ghci_mode == Interactive) && not source_unchanged then
873          returnM (outOfDate, maybe_iface)
874     else
875
876     case maybe_iface of
877        Just old_iface -> -- Use the one we already have
878                          checkVersions source_unchanged old_iface       `thenM` \ recomp ->
879                          returnM (recomp, Just old_iface)
880
881        Nothing          -- Try and read it from a file
882           -> getModule                                  `thenM` \ this_mod ->
883              readIface this_mod iface_path False        `thenM` \ read_result ->
884              case read_result of
885                Left err -> -- Old interface file not found, or garbled; give up
886                            traceHiDiffs (
887                                 text "Cannot read old interface file:"
888                                    $$ nest 4 (text (showException err))) `thenM_`
889                            returnM (outOfDate, Nothing)
890
891                Right parsed_iface ->
892                          initRn (InterfaceMode this_mod)
893                                 (loadOldIface parsed_iface)     `thenM` \ m_iface ->
894                          checkVersions source_unchanged m_iface `thenM` \ recomp ->
895                          returnM (recomp, Just m_iface)
896 \end{code}
897
898
899 %************************************************************************
900 %*                                                                      *
901         Type-check and rename supporting declarations
902         This is used to deal with the free vars of a splice,
903         or derived code: slurp in the necessary declarations,
904         typecheck them, and add them to the EPS
905 %*                                                                      *
906 %************************************************************************
907
908 \begin{code}
909 importSupportingDecls :: FreeVars -> TcM TcGblEnv
910 -- Completely deal with the supporting imports needed
911 -- by the specified free-var set
912 importSupportingDecls fvs
913  = do { traceRn (text "Import supporting decls for" <+> ppr (nameSetToList fvs)) ;
914         decls <- slurpImpDecls fvs ;
915         traceRn (text "...namely:" <+> vcat (map ppr decls)) ;
916         typecheckIfaceDecls (mkGroup decls) }
917
918 typecheckIfaceDecls :: HsGroup Name -> TcM TcGblEnv
919   -- The decls are all interface-file declarations
920   -- Usually they are all from other modules, but when we are reading
921   -- this module's interface from a file, it's possible that some of
922   -- them are for the module being compiled.
923   -- That is why the tcExtendX functions need to do partitioning.
924   --
925   -- If all the decls are from other modules, the returned TcGblEnv
926   -- will have an empty tc_genv, but its tc_inst_env and tc_ist 
927   -- caches may have been augmented.
928 typecheckIfaceDecls (HsGroup { hs_tyclds = tycl_decls,
929                                hs_instds = inst_decls,
930                                hs_ruleds = rule_decls })
931  = do {         -- Typecheck the type, class, and interface-sig decls
932         tcg_env <- fixM (\ unf_env -> tcTyClDecls unf_env tycl_decls) ;
933         setGblEnv tcg_env               $ do {
934         
935         -- Typecheck the instance decls, and rules
936         -- Note that imported dictionary functions are already
937         -- in scope from the preceding tcTyClDecls
938         tcIfaceInstDecls inst_decls     `thenM` \ dfuns ->
939         tcExtendInstEnv dfuns           $
940         tcRules rule_decls              `thenM` \ rules ->
941         tcExtendRules rules             $
942     
943         getGblEnv               -- Return the environment
944    }}
945 \end{code}
946
947
948
949 %*********************************************************
950 %*                                                       *
951         mkGlobalContext: make up an interactive context
952
953         Used for initialising the lexical environment
954         of the interactive read-eval-print loop
955 %*                                                       *
956 %*********************************************************
957
958 \begin{code}
959 #ifdef GHCI
960 mkGlobalContext
961         :: HscEnv -> PersistentCompilerState
962         -> [Module]     -- Expose these modules' top-level scope
963         -> [Module]     -- Expose these modules' exports only
964         -> IO (PersistentCompilerState, Maybe GlobalRdrEnv)
965
966 mkGlobalContext hsc_env pcs toplevs exports
967   = initTc hsc_env pcs iNTERACTIVE $ do {
968
969     toplev_envs <- mappM getTopLevScope   toplevs ;
970     export_envs <- mappM getModuleExports exports ;
971     returnM (foldr plusGlobalRdrEnv emptyGlobalRdrEnv
972                    (toplev_envs ++ export_envs))
973     }
974
975 getTopLevScope :: Module -> TcRn m GlobalRdrEnv
976 getTopLevScope mod
977   = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
978          case mi_globals iface of
979                 Nothing  -> panic "getTopLevScope"
980                 Just env -> returnM env }
981
982 getModuleExports :: Module -> TcRn m GlobalRdrEnv
983 getModuleExports mod 
984   = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
985          returnM (foldl add emptyGlobalRdrEnv (mi_exports iface)) }
986   where
987     prov_fn n = NonLocalDef ImplicitImport
988     add env (mod,avails)
989         = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True prov_fn avails NoDeprecs)
990
991 contextDoc = text "context for compiling statements"
992 \end{code}
993
994 \begin{code}
995 getModuleContents
996   :: HscEnv
997   -> PersistentCompilerState    -- IN: persistent compiler state
998   -> Module                     -- module to inspect
999   -> Bool                       -- grab just the exports, or the whole toplev
1000   -> IO (PersistentCompilerState, Maybe [TyThing])
1001
1002 getModuleContents hsc_env pcs mod exports_only
1003  = initTc hsc_env pcs iNTERACTIVE $ do {   
1004
1005         -- Load the interface if necessary (a home module will certainly
1006         -- alraedy be loaded, but a package module might not be)
1007         iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
1008
1009         let { export_names = availsToNameSet export_avails ;
1010               export_avails = [ avail | (mn, avails) <- mi_exports iface, 
1011                                         avail <- avails ] } ;
1012
1013         all_names <- if exports_only then 
1014                         return export_names
1015                      else case mi_globals iface of {
1016                            Just rdr_env -> 
1017                                 return (get_locals rdr_env) ;
1018
1019                            Nothing -> do { addErr (noRdrEnvErr mod) ;
1020                                            return export_names } } ;
1021                                 -- Invariant; we only have (not exports_only) 
1022                                 -- for a home module so it must already be in the HIT
1023                                 -- So the Nothing case is a bug
1024
1025         env <- importSupportingDecls all_names ;
1026         setGblEnv env (mappM tcLookupGlobal (nameSetToList all_names))
1027     }
1028   where
1029         -- Grab all the things from the global env that are locally def'd
1030     get_locals rdr_env = mkNameSet [ gre_name gre
1031                                    | elts <- rdrEnvElts rdr_env, 
1032                                      gre <- elts, 
1033                                      isLocalGRE gre ]
1034         -- Make a set because a name is often in the envt in
1035         -- both qualified and unqualified forms
1036
1037 noRdrEnvErr mod = ptext SLIT("No top-level environment available for module") 
1038                   <+> quotes (ppr mod)
1039 #endif
1040 \end{code}
1041
1042 %************************************************************************
1043 %*                                                                      *
1044         Checking for 'main'
1045 %*                                                                      *
1046 %************************************************************************
1047
1048 \begin{code}
1049 checkMain 
1050   = do { ghci_mode <- getGhciMode ;
1051          tcg_env   <- getGblEnv ;
1052          check_main ghci_mode tcg_env
1053     }
1054
1055 check_main ghci_mode tcg_env
1056      -- If we are in module Main, check that 'main' is defined.
1057      -- It may be imported from another module, in which case 
1058      -- we have to drag in its.
1059      -- 
1060      -- Also form the definition
1061      --         $main = runIO main
1062      -- so we need to slurp in runIO too.
1063      --
1064      -- ToDo: We have to return the main_name separately, because it's a
1065      -- bona fide 'use', and should be recorded as such, but the others
1066      -- aren't 
1067      -- 
1068      -- Blimey: a whole page of code to do this...
1069
1070  | mod_name /= mAIN_Name
1071  = return (tcg_env, emptyFVs)
1072
1073  | not (main_RDR_Unqual `elemRdrEnv` rdr_env)
1074  = do { complain_no_main; return (tcg_env, emptyFVs) }
1075
1076  | otherwise
1077  = do {         -- Check that 'main' is in scope
1078                 -- It might be imported from another module!
1079         main_name <- lookupSrcName main_RDR_Unqual ;
1080         failIfErrsM ;
1081
1082         tcg_env <- importSupportingDecls (unitFV runIOName) ;
1083         setGblEnv tcg_env $ do {
1084         
1085         -- $main :: IO () = runIO main
1086         let { rhs = HsApp (HsVar runIOName) (HsVar main_name) } ;
1087
1088         (main_bind, top_lie) <- getLIE (
1089                 addSrcLoc (getSrcLoc main_name) $
1090                 addErrCtxt mainCtxt             $ do {
1091                 (main_expr, ty) <- tcExpr_id rhs ;
1092                 let { dollar_main_id = setIdLocalExported (mkLocalId dollarMainName ty) } ;
1093                 return (VarMonoBind dollar_main_id main_expr)
1094             }) ;
1095
1096         inst_binds <- tcSimplifyTop top_lie ;
1097
1098         (ids, binds') <- zonkTopBinds (main_bind `andMonoBinds` inst_binds) ;
1099         
1100         let { tcg_env' = tcg_env { 
1101                 tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) ids,
1102                 tcg_binds = tcg_binds tcg_env `andMonoBinds` binds' } } ;
1103
1104         return (tcg_env', unitFV main_name)
1105     }}
1106   where
1107     mod_name = moduleName (tcg_mod tcg_env) 
1108     rdr_env  = tcg_rdr_env tcg_env
1109  
1110     main_RDR_Unqual :: RdrName
1111     main_RDR_Unqual = mkUnqual varName FSLIT("main")
1112         -- Don't get a RdrName from PrelNames.mainName, because 
1113         -- nameRdrNamegets an Orig RdrName, and we want a Qual or Unqual one.  
1114         -- An Unqual one will do just fine
1115
1116     complain_no_main | ghci_mode == Interactive = return ()
1117                      | otherwise                = addErr noMainMsg
1118         -- In interactive mode, don't worry about the absence of 'main'
1119
1120     mainCtxt  = ptext SLIT("When checking the type of 'main'")
1121     noMainMsg = ptext SLIT("No 'main' defined in module Main")
1122 \end{code}
1123
1124
1125 %************************************************************************
1126 %*                                                                      *
1127                 Degugging output
1128 %*                                                                      *
1129 %************************************************************************
1130
1131 \begin{code}
1132 rnDump :: SDoc -> TcRn m ()
1133 -- Dump, with a banner, if -ddump-rn
1134 rnDump doc = dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc)
1135
1136 tcDump :: TcGblEnv -> TcRn m ()
1137 tcDump env
1138  = do { dflags <- getDOpts ;
1139
1140         -- Dump short output if -ddump-types or -ddump-tc
1141         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1142             (dumpTcRn short_dump) ;
1143
1144         -- Dump bindings if -ddump-tc
1145         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1146    }
1147   where
1148     short_dump = pprTcGblEnv env
1149     full_dump  = ppr (tcg_binds env)
1150         -- NB: foreign x-d's have undefined's in their types; 
1151         --     hence can't show the tc_fords
1152
1153 tcCoreDump mod_guts
1154  = do { dflags <- getDOpts ;
1155         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1156             (dumpTcRn (pprModGuts mod_guts)) ;
1157
1158         -- Dump bindings if -ddump-tc
1159         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1160   where
1161     full_dump = pprCoreBindings (mg_binds mod_guts)
1162
1163 -- It's unpleasant having both pprModGuts and pprModDetails here
1164 pprTcGblEnv :: TcGblEnv -> SDoc
1165 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env, 
1166                         tcg_insts    = dfun_ids, 
1167                         tcg_rules    = rules })
1168   = vcat [ ppr_types dfun_ids type_env
1169          , ppr_insts dfun_ids
1170          , vcat (map ppr rules)
1171          , ppr_gen_tycons (typeEnvTyCons type_env)]
1172
1173 pprModGuts :: ModGuts -> SDoc
1174 pprModGuts (ModGuts { mg_types = type_env,
1175                       mg_rules = rules })
1176   = vcat [ ppr_types [] type_env,
1177            ppr_rules rules ]
1178
1179
1180 ppr_types :: [Var] -> TypeEnv -> SDoc
1181 ppr_types dfun_ids type_env
1182   = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1183   where
1184     ids = [id | id <- typeEnvIds type_env, want_sig id]
1185     want_sig id | opt_PprStyle_Debug = True
1186                 | otherwise          = isLocalId id && 
1187                                        isExternalName (idName id) && 
1188                                        not (id `elem` dfun_ids)
1189         -- isLocalId ignores data constructors, records selectors etc.
1190         -- The isExternalName ignores local dictionary and method bindings
1191         -- that the type checker has invented.  Top-level user-defined things 
1192         -- have External names.
1193
1194 ppr_insts :: [Var] -> SDoc
1195 ppr_insts []       = empty
1196 ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)
1197
1198 ppr_sigs :: [Var] -> SDoc
1199 ppr_sigs ids
1200         -- Print type signatures
1201         -- Convert to HsType so that we get source-language style printing
1202         -- And sort by RdrName
1203   = vcat $ map ppr_sig $ sortLt lt_sig $
1204     [ (getRdrName id, toHsType (idType id))
1205     | id <- ids ]
1206   where
1207     lt_sig (n1,_) (n2,_) = n1 < n2
1208     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
1209
1210
1211 ppr_rules :: [IdCoreRule] -> SDoc
1212 ppr_rules [] = empty
1213 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1214                       nest 4 (pprIdRules rs),
1215                       ptext SLIT("#-}")]
1216
1217 ppr_gen_tycons []  = empty
1218 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
1219                            vcat (map ppr_gen_tycon tcs),
1220                            ptext SLIT("#-}")
1221                      ]
1222
1223 -- x&y are now Id's, not CoreExpr's 
1224 ppr_gen_tycon tycon 
1225   | Just ep <- tyConGenInfo tycon
1226   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
1227
1228   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
1229
1230 ppr_ep (EP from to)
1231   = vcat [ ptext SLIT("Rep type:") <+> ppr (tcFunResultTy from_tau),
1232            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
1233            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
1234     ]
1235   where
1236     (_,from_tau) = tcSplitForAllTys (idType from)
1237 \end{code}