[project @ 2002-11-21 09:37:24 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 import                DsMeta   ( templateHaskellNames )
21 #endif
22
23 import CmdLineOpts      ( DynFlag(..), opt_PprStyle_Debug, dopt )
24 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsExpr(..),
25                           Stmt(..), Pat(VarPat), HsStmtContext(..), RuleDecl(..),
26                           HsGroup(..), SpliceDecl(..),
27                           mkSimpleMatch, placeHolderType, toHsType, andMonoBinds,
28                           isSrcRule, collectStmtsBinders
29                         )
30 import RdrHsSyn         ( RdrNameHsModule, RdrNameHsDecl, RdrNameStmt, RdrNameHsExpr,
31                           emptyGroup, mkGroup, findSplice, addImpDecls )
32
33 import PrelNames        ( iNTERACTIVE, ioTyConName, printName,
34                           returnIOName, bindIOName, failIOName, thenIOName, runIOName, 
35                           dollarMainName, itName, mAIN_Name
36                         )
37 import MkId             ( unsafeCoerceId )
38 import RdrName          ( RdrName, getRdrName, mkUnqual, mkRdrUnqual, 
39                           lookupRdrEnv, elemRdrEnv )
40
41 import RnHsSyn          ( RenamedStmt, RenamedTyClDecl, 
42                           ruleDeclFVs, instDeclFVs, tyClDeclFVs )
43 import TcHsSyn          ( TypecheckedHsExpr, TypecheckedRuleDecl,
44                           zonkTopBinds, zonkTopDecls, mkHsLet,
45                           zonkTopExpr, zonkTopBndrs
46                         )
47
48 import TcExpr           ( tcExpr_id )
49 import TcRnMonad
50 import TcMType          ( newTyVarTy, zonkTcType )
51 import TcType           ( Type, liftedTypeKind, 
52                           tyVarsOfType, tcFunResultTy,
53                           mkForAllTys, mkFunTys, mkTyConApp, tcSplitForAllTys
54                         )
55 import TcMatches        ( tcStmtsAndThen )
56 import Inst             ( showLIE )
57 import TcBinds          ( tcTopBinds )
58 import TcClassDcl       ( tcClassDecls2 )
59 import TcDefaults       ( tcDefaults )
60 import TcEnv            ( RecTcGblEnv, 
61                           tcExtendGlobalValEnv, 
62                           tcExtendGlobalEnv,
63                           tcExtendInstEnv, tcExtendRules,
64                           tcLookupTyCon, tcLookupGlobal,
65                           tcLookupId 
66                         )
67 import TcRules          ( tcRules )
68 import TcForeign        ( tcForeignImports, tcForeignExports )
69 import TcIfaceSig       ( tcInterfaceSigs, tcCoreBinds )
70 import TcInstDcls       ( tcInstDecls1, tcIfaceInstDecls, tcInstDecls2 )
71 import TcSimplify       ( tcSimplifyTop, tcSimplifyInfer )
72 import TcTyClsDecls     ( tcTyAndClassDecls )
73
74 import RnNames          ( rnImports, exportsFromAvail, reportUnusedNames )
75 import RnIfaces         ( slurpImpDecls, checkVersions, RecompileRequired, outOfDate )
76 import RnHiFiles        ( readIface, loadOldIface )
77 import RnEnv            ( lookupSrcName, lookupOccRn, plusGlobalRdrEnv,
78                           ubiquitousNames, implicitModuleFVs, implicitStmtFVs, dataTcOccs )
79 import RnExpr           ( rnStmts, rnExpr )
80 import RnNames          ( importsFromLocalDecls )
81 import RnSource         ( rnSrcDecls, checkModDeprec, rnStats )
82
83 import OccName          ( varName )
84 import CoreUnfold       ( unfoldingTemplate )
85 import CoreSyn          ( IdCoreRule, Bind(..) )
86 import PprCore          ( pprIdRules, pprCoreBindings )
87 import TysWiredIn       ( mkListTy, unitTy )
88 import ErrUtils         ( mkDumpDoc, showPass )
89 import Id               ( Id, mkLocalId, isLocalId, idName, idType, idUnfolding, setIdLocalExported )
90 import IdInfo           ( GlobalIdDetails(..) )
91 import Var              ( Var, setGlobalIdDetails )
92 import Module           ( Module, moduleName, moduleUserString, moduleEnvElts )
93 import Name             ( Name, isExternalName, getSrcLoc, nameOccName )
94 import NameEnv          ( delListFromNameEnv )
95 import NameSet
96 import TyCon            ( tyConGenInfo )
97 import BasicTypes       ( EP(..), RecFlag(..) )
98 import SrcLoc           ( noSrcLoc )
99 import Outputable
100 import HscTypes         ( PersistentCompilerState(..), InteractiveContext(..),
101                           ModIface, ModDetails(..), ModGuts(..),
102                           HscEnv(..), 
103                           ModIface(..), ModDetails(..), IfaceDecls(..),
104                           GhciMode(..), noDependencies,
105                           Deprecations(..), plusDeprecs,
106                           emptyGlobalRdrEnv,
107                           GenAvailInfo(Avail), availsToNameSet, 
108                           ForeignStubs(..),
109                           TypeEnv, TyThing, typeEnvTyCons, 
110                           extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
111                           extendLocalRdrEnv, emptyFixityEnv
112                         )
113 #ifdef GHCI
114 import RdrName          ( rdrEnvElts )
115 import RnHiFiles        ( loadInterface )
116 import RnEnv            ( mkGlobalRdrEnv )
117 import HscTypes         ( GlobalRdrElt(..), GlobalRdrEnv, ImportReason(..), Provenance(..), 
118                           isLocalGRE )
119 #endif
120
121 import Maybe            ( catMaybes )
122 import Panic            ( showException )
123 import List             ( partition )
124 import Util             ( sortLt )
125 \end{code}
126
127
128
129 %************************************************************************
130 %*                                                                      *
131         Typecheck and rename a module
132 %*                                                                      *
133 %************************************************************************
134
135
136 \begin{code}
137 tcRnModule :: HscEnv -> PersistentCompilerState
138            -> RdrNameHsModule 
139            -> IO (PersistentCompilerState, Maybe TcGblEnv)
140
141 tcRnModule hsc_env pcs
142            (HsModule this_mod _ exports import_decls local_decls mod_deprec loc)
143  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
144
145    initTc hsc_env pcs this_mod $ addSrcLoc loc $
146    do {         -- Deal with imports; sets tcg_rdr_env, tcg_imports
147         (rdr_env, imports) <- rnImports import_decls ;
148         updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
149                                    tcg_imports = tcg_imports gbl `plusImportAvails` imports }) 
150                      $ do {
151         traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
152                 -- Fail if there are any errors so far
153                 -- The error printing (if needed) takes advantage 
154                 -- of the tcg_env we have now set
155         failIfErrsM ;
156
157         traceRn (text "rn1a") ;
158                 -- Rename and type check the declarations
159         (tcg_env, src_fvs) <- tcRnSrcDecls local_decls ;
160         setGblEnv tcg_env               $ do {
161         traceRn (text "rn2") ;
162
163                 -- Check for 'main'
164         (tcg_env, main_fvs) <- checkMain ;
165         setGblEnv tcg_env               $ do {
166
167         traceRn (text "rn3") ;
168                 -- Check whether the entire module is deprecated
169                 -- This happens only once per module
170                 -- Returns the full new deprecations; a module deprecation 
171                 --      over-rides the earlier ones
172         let { mod_deprecs = checkModDeprec mod_deprec } ;
173         updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` mod_deprecs })
174                   $ do {
175
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         -- Add deprecation warnings
490     mapM_ addMessages msgs_s ;  
491
492         -- Slurp in the supporting declarations
493     tcg_env <- importSupportingDecls (mkFVs names) ;
494     setGblEnv tcg_env $ do {
495
496         -- And lookup up the entities
497     mapM tcLookupGlobal names
498     }}}
499 \end{code}
500
501
502 \begin{code}
503 setInteractiveContext :: InteractiveContext -> TcRn m a -> TcRn m a
504 setInteractiveContext icxt thing_inside 
505   = traceTc (text "setIC" <+> ppr (ic_type_env icxt))   `thenM_`
506     updGblEnv (\ env -> env { tcg_rdr_env  = ic_rn_gbl_env icxt,
507                               tcg_type_env = ic_type_env   icxt })
508               thing_inside
509
510 initRnInteractive :: InteractiveContext -> RnM a -> TcM a
511 -- Set the local RdrEnv from the interactive context
512 initRnInteractive ictxt rn_thing
513   = initRn CmdLineMode $
514     setLocalRdrEnv (ic_rn_local_env ictxt) $
515     rn_thing
516 \end{code}
517
518 %************************************************************************
519 %*                                                                      *
520         Type-checking external-core modules
521 %*                                                                      *
522 %************************************************************************
523
524 \begin{code}
525 tcRnExtCore :: HscEnv -> PersistentCompilerState 
526             -> RdrNameHsModule 
527             -> IO (PersistentCompilerState, Maybe ModGuts)
528         -- Nothing => some error occurred 
529
530 tcRnExtCore hsc_env pcs 
531             (HsModule this_mod _ _ _ local_decls _ loc)
532         -- Rename the (Core) module.  It's a bit like an interface
533         -- file: all names are original names
534  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
535
536    initTc hsc_env pcs this_mod $ addSrcLoc loc $ do {
537
538         -- Rename the source, only in interface mode.
539         -- rnSrcDecls handles fixity decls etc too, which won't occur
540         -- but that doesn't matter
541    let { local_group = mkGroup local_decls } ;
542    (_, rn_local_decls, fvs) <- initRn (InterfaceMode this_mod) 
543                                       (rnSrcDecls local_group) ;
544    failIfErrsM ;
545
546         -- Get the supporting decls, and typecheck them all together
547         -- so that any mutually recursive types are done right
548    extra_decls <- slurpImpDecls fvs ;
549    tcg_env <- typecheckIfaceDecls (rn_local_decls `addImpDecls` extra_decls) ;
550    setGblEnv tcg_env $ do {
551    
552         -- Now the core bindings
553    core_prs <- tcCoreBinds (hs_coreds rn_local_decls) ;
554    tcExtendGlobalValEnv (map fst core_prs) $ do {
555    
556         -- Wrap up
557    let {
558         bndrs      = map fst core_prs ;
559         my_exports = map (Avail . idName) bndrs ;
560                 -- ToDo: export the data types also?
561
562         final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
563
564         mod_guts = ModGuts {    mg_module   = this_mod,
565                                 mg_usages   = [],       -- ToDo: compute usage
566                                 mg_dir_imps = [],       -- ??
567                                 mg_deps     = noDependencies,   -- ??
568                                 mg_exports  = my_exports,
569                                 mg_types    = final_type_env,
570                                 mg_insts    = tcg_insts tcg_env,
571                                 mg_rules    = hsCoreRules (tcg_rules tcg_env),
572                                 mg_binds    = [Rec core_prs],
573
574                                 -- Stubs
575                                 mg_rdr_env  = emptyGlobalRdrEnv,
576                                 mg_fix_env  = emptyFixityEnv,
577                                 mg_deprecs  = NoDeprecs,
578                                 mg_foreign  = NoStubs
579                     } } ;
580
581    tcCoreDump mod_guts ;
582
583    return mod_guts
584    }}}}
585 \end{code}
586
587
588 %************************************************************************
589 %*                                                                      *
590         Type-checking the top level of a module
591 %*                                                                      *
592 %************************************************************************
593
594 \begin{code}
595 tcRnSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, FreeVars)
596         -- Returns the variables free in the decls
597         -- Reason: solely to report unused imports and bindings
598 tcRnSrcDecls [] = do { tcg_env <- getGblEnv ; return (tcg_env, emptyFVs) }
599 tcRnSrcDecls ds
600  = do { let { (first_group, group_tail) = findSplice ds } ;
601
602         -- Type check the decls up to, but not including, the first splice
603         (tcg_env, src_fvs1) <- tcRnGroup first_group ;
604
605         -- If there is no splice, we're done
606         case group_tail of
607            Nothing -> return (tcg_env, src_fvs1)
608            Just (SpliceDecl splice_expr splice_loc, rest_ds) -> do {
609
610         setGblEnv tcg_env $ do {
611
612 #ifndef GHCI
613         failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
614 #else
615         -- Rename the splice expression, and get its supporting decls
616         (rn_splice_expr, fvs) <- initRn SourceMode $
617                                  addSrcLoc splice_loc $
618                                  rnExpr splice_expr ;
619         tcg_env <- importSupportingDecls (fvs `plusFV` templateHaskellNames) ;
620         setGblEnv tcg_env $ do {
621
622         -- Execute the splice
623         spliced_decls <- tcSpliceDecls rn_splice_expr ;
624
625         -- Glue them on the front of the remaining decls and loop
626         (tcg_env, src_fvs2) <- tcRnSrcDecls (spliced_decls ++ rest_ds) ;
627
628         return (tcg_env, src_fvs1 `plusFV` src_fvs2)
629     }
630 #endif /* GHCI */
631     }}}
632 \end{code}
633
634
635 %************************************************************************
636 %*                                                                      *
637         Type-checking the top level of a module
638 %*                                                                      *
639 %************************************************************************
640
641 tcRnGroup takes a bunch of top-level source-code declarations, and
642  * renames them
643  * gets supporting declarations from interface files
644  * typechecks them
645  * zonks them
646  * and augments the TcGblEnv with the results
647
648 In Template Haskell it may be called repeatedly for each group of
649 declarations.  It expects there to be an incoming TcGblEnv in the
650 monad; it augments it and returns the new TcGblEnv.
651
652 \begin{code}
653 tcRnGroup :: HsGroup RdrName -> TcM (TcGblEnv, FreeVars)
654         -- Returns the variables free in the decls
655 tcRnGroup decls
656  = do {         -- Rename the declarations
657         (tcg_env, rn_decls, src_fvs) <- rnTopSrcDecls decls ;
658         setGblEnv tcg_env $ do {
659
660                 -- Typecheck the declarations
661         tcg_env <- tcTopSrcDecls rn_decls ;
662         return (tcg_env, src_fvs)
663   }}
664
665 ------------------------------------------------
666 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name, FreeVars)
667 rnTopSrcDecls group
668  = do {         -- Bring top level binders into scope
669         (rdr_env, imports) <- importsFromLocalDecls group ;
670         updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv`
671                                                   tcg_rdr_env gbl,
672                                  tcg_imports = imports `plusImportAvails` 
673                                                   tcg_imports gbl }) 
674                      $ do {
675
676         failIfErrsM ;   -- No point in continuing if (say) we have duplicate declarations
677
678                 -- Rename the source decls
679         (tcg_env, rn_src_decls, src_fvs) <- initRn SourceMode (rnSrcDecls group) ;
680         setGblEnv tcg_env $ do {
681
682         failIfErrsM ;
683
684                 -- Import consquential imports
685         rn_imp_decls <- slurpImpDecls (src_fvs `plusFV` implicitModuleFVs src_fvs) ;
686         let { rn_decls = rn_src_decls `addImpDecls` rn_imp_decls } ;
687
688                 -- Dump trace of renaming part
689         rnDump (ppr rn_decls) ;
690         rnStats rn_imp_decls ;
691
692         return (tcg_env, rn_decls, src_fvs)
693   }}}
694
695 ------------------------------------------------
696 tcTopSrcDecls :: HsGroup Name -> TcM TcGblEnv
697 tcTopSrcDecls rn_decls
698  = fixM (\ unf_env -> do {      
699         -- Loop back the final environment, including the fully zonked
700         -- versions of bindings from this module.  In the presence of mutual
701         -- recursion, interface type signatures may mention variables defined
702         -- in this module, which is why the knot is so big
703
704                         -- Do the main work
705         ((tcg_env, binds, rules, fords), lie) <- getLIE (
706                 tc_src_decls unf_env rn_decls
707             ) ;
708
709              -- tcSimplifyTop deals with constant or ambiguous InstIds.  
710              -- How could there be ambiguous ones?  They can only arise if a
711              -- top-level decl falls under the monomorphism
712              -- restriction, and no subsequent decl instantiates its
713              -- type.  (Usually, ambiguous type variables are resolved
714              -- during the generalisation step.)
715         traceTc (text "Tc8") ;
716         inst_binds <- setGblEnv tcg_env (tcSimplifyTop lie) ;
717                 -- The setGblEnv exposes the instances to tcSimplifyTop
718
719             -- Backsubstitution.  This must be done last.
720             -- Even tcSimplifyTop may do some unification.
721         traceTc (text "Tc9") ;
722         (ids, binds', fords', rules') <- zonkTopDecls (binds `andMonoBinds` inst_binds)
723                                                       rules fords ;
724
725         let { tcg_env' = tcg_env { tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) ids,
726                                    tcg_binds = tcg_binds tcg_env `andMonoBinds` binds',
727                                    tcg_rules = tcg_rules tcg_env ++ rules',
728                                    tcg_fords = tcg_fords tcg_env ++ fords' } } ;
729         
730         return tcg_env' 
731     })
732
733 tc_src_decls unf_env 
734         (HsGroup { hs_tyclds = tycl_decls, 
735                    hs_instds = inst_decls,
736                    hs_fords  = foreign_decls,
737                    hs_defds  = default_decls,
738                    hs_ruleds = rule_decls,
739                    hs_valds  = val_binds })
740  = do {         -- Type-check the type and class decls, and all imported decls
741         traceTc (text "Tc2") ;
742         tcg_env <- tcTyClDecls unf_env tycl_decls ;
743         setGblEnv tcg_env       $ do {
744
745                 -- Source-language instances, including derivings,
746                 -- and import the supporting declarations
747         traceTc (text "Tc3") ;
748         (tcg_env, inst_infos, deriv_binds, fvs) <- tcInstDecls1 tycl_decls inst_decls ;
749         setGblEnv tcg_env       $ do {
750         tcg_env <- importSupportingDecls fvs ;
751         setGblEnv tcg_env       $ do {
752
753                 -- Foreign import declarations next.  No zonking necessary
754                 -- here; we can tuck them straight into the global environment.
755         traceTc (text "Tc4") ;
756         (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
757         tcExtendGlobalValEnv fi_ids                  $
758         updGblEnv (\gbl -> gbl { tcg_fords = tcg_fords gbl ++ fi_decls }) 
759                   $ do {
760
761                 -- Default declarations
762         traceTc (text "Tc4a") ;
763         default_tys <- tcDefaults default_decls ;
764         updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
765         
766                 -- Value declarations next
767                 -- We also typecheck any extra binds that came out 
768                 -- of the "deriving" process
769         traceTc (text "Tc5") ;
770         (tc_val_binds, lcl_env) <- tcTopBinds (val_binds `ThenBinds` deriv_binds) ;
771         setLclTypeEnv lcl_env   $ do {
772
773                 -- Second pass over class and instance declarations, 
774                 -- plus rules and foreign exports, to generate bindings
775         traceTc (text "Tc6") ;
776         (cls_dm_binds, dm_ids) <- tcClassDecls2 tycl_decls ;
777         tcExtendGlobalValEnv dm_ids     $ do {
778         inst_binds <- tcInstDecls2 inst_infos ;
779         showLIE "after instDecls2" ;
780
781                 -- Foreign exports
782                 -- They need to be zonked, so we return them
783         traceTc (text "Tc7") ;
784         (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
785
786                 -- Rules
787                 -- Need to partition them because the source rules
788                 -- must be zonked before adding them to tcg_rules
789                 -- NB: built-in rules come in as IfaceRuleOut's, and
790                 --     get added to tcg_rules right here by tcExtendRules
791         rules <- tcRules rule_decls ;
792         let { (src_rules, iface_rules) = partition isSrcRule rules } ;
793         tcExtendRules iface_rules $ do {
794
795                 -- Wrap up
796         tcg_env <- getGblEnv ;
797         let { all_binds = tc_val_binds   `AndMonoBinds`
798                           inst_binds     `AndMonoBinds`
799                           cls_dm_binds   `AndMonoBinds`
800                           foe_binds } ;
801
802         return (tcg_env, all_binds, src_rules, foe_decls)
803      }}}}}}}}}
804 \end{code}
805
806 \begin{code}
807 tcTyClDecls :: RecTcGblEnv
808             -> [RenamedTyClDecl]
809             -> TcM TcGblEnv
810
811 -- tcTyClDecls deals with 
812 --      type and class decls (some source, some imported)
813 --      interface signatures (checked lazily)
814 --
815 -- It returns the TcGblEnv for this module, and side-effects the
816 -- persistent compiler state to reflect the things imported from
817 -- other modules
818
819 tcTyClDecls unf_env tycl_decls
820   -- (unf_env :: RecTcGblEnv) is used for type-checking interface pragmas
821   -- which is done lazily [ie failure just drops the pragma
822   -- without having any global-failure effect].
823
824   = checkNoErrs $
825         -- tcTyAndClassDecls recovers internally, but if anything gave rise to
826         -- an error we'd better stop now, to avoid a cascade
827         
828     traceTc (text "TyCl1")              `thenM_`
829     tcTyAndClassDecls tycl_decls        `thenM` \ tycl_things ->
830     tcExtendGlobalEnv tycl_things       $
831     
832         -- Interface type signatures
833         -- We tie a knot so that the Ids read out of interfaces are in scope
834         --   when we read their pragmas.
835         -- What we rely on is that pragmas are typechecked lazily; if
836         --   any type errors are found (ie there's an inconsistency)
837         --   we silently discard the pragma
838     traceTc (text "TyCl2")                      `thenM_`
839     tcInterfaceSigs unf_env tycl_decls          `thenM` \ sig_ids ->
840     tcExtendGlobalValEnv sig_ids                $
841     
842     getGblEnv           -- Return the TcLocals environment
843 \end{code}    
844
845
846
847 %************************************************************************
848 %*                                                                      *
849         Load the old interface file for this module (unless
850         we have it aleady), and check whether it is up to date
851         
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 checkOldIface :: HscEnv
857               -> PersistentCompilerState
858               -> Module
859               -> FilePath               -- Where the interface file is
860               -> Bool                   -- Source unchanged
861               -> Maybe ModIface         -- Old interface from compilation manager, if any
862               -> IO (PersistentCompilerState, Maybe (RecompileRequired, Maybe ModIface))
863                                 -- Nothing <=> errors happened
864
865 checkOldIface hsc_env pcs mod iface_path source_unchanged maybe_iface
866   = do { showPass (hsc_dflags hsc_env) 
867                   ("Checking old interface for " ++ moduleUserString mod) ;
868
869          initTc hsc_env pcs mod
870                 (check_old_iface iface_path source_unchanged maybe_iface)
871      }
872
873 check_old_iface iface_path source_unchanged maybe_iface
874  =      -- CHECK WHETHER THE SOURCE HAS CHANGED
875     ifM (not source_unchanged)
876         (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
877                                                 `thenM_`
878
879      -- If the source has changed and we're in interactive mode, avoid reading
880      -- an interface; just return the one we might have been supplied with.
881     getGhciMode                                 `thenM` \ ghci_mode ->
882     if (ghci_mode == Interactive) && not source_unchanged then
883          returnM (outOfDate, maybe_iface)
884     else
885
886     case maybe_iface of
887        Just old_iface -> -- Use the one we already have
888                          checkVersions source_unchanged old_iface       `thenM` \ recomp ->
889                          returnM (recomp, Just old_iface)
890
891        Nothing          -- Try and read it from a file
892           -> getModule                                  `thenM` \ this_mod ->
893              readIface this_mod iface_path False        `thenM` \ read_result ->
894              case read_result of
895                Left err -> -- Old interface file not found, or garbled; give up
896                            traceHiDiffs (
897                                 text "Cannot read old interface file:"
898                                    $$ nest 4 (text (showException err))) `thenM_`
899                            returnM (outOfDate, Nothing)
900
901                Right parsed_iface ->
902                          initRn (InterfaceMode this_mod)
903                                 (loadOldIface parsed_iface)     `thenM` \ m_iface ->
904                          checkVersions source_unchanged m_iface `thenM` \ recomp ->
905                          returnM (recomp, Just m_iface)
906 \end{code}
907
908
909 %************************************************************************
910 %*                                                                      *
911         Type-check and rename supporting declarations
912         This is used to deal with the free vars of a splice,
913         or derived code: slurp in the necessary declarations,
914         typecheck them, and add them to the EPS
915 %*                                                                      *
916 %************************************************************************
917
918 \begin{code}
919 importSupportingDecls :: FreeVars -> TcM TcGblEnv
920 -- Completely deal with the supporting imports needed
921 -- by the specified free-var set
922 importSupportingDecls fvs
923  = do { traceRn (text "Import supporting decls for" <+> ppr (nameSetToList fvs)) ;
924         decls <- slurpImpDecls fvs ;
925         traceRn (text "...namely:" <+> vcat (map ppr decls)) ;
926         typecheckIfaceDecls (mkGroup decls) }
927
928 typecheckIfaceDecls :: HsGroup Name -> TcM TcGblEnv
929   -- The decls are all interface-file declarations
930   -- Usually they are all from other modules, but when we are reading
931   -- this module's interface from a file, it's possible that some of
932   -- them are for the module being compiled.
933   -- That is why the tcExtendX functions need to do partitioning.
934   --
935   -- If all the decls are from other modules, the returned TcGblEnv
936   -- will have an empty tc_genv, but its tc_inst_env and tc_ist 
937   -- caches may have been augmented.
938 typecheckIfaceDecls (HsGroup { hs_tyclds = tycl_decls,
939                                hs_instds = inst_decls,
940                                hs_ruleds = rule_decls })
941  = do {         -- Typecheck the type, class, and interface-sig decls
942         tcg_env <- fixM (\ unf_env -> tcTyClDecls unf_env tycl_decls) ;
943         setGblEnv tcg_env               $ do {
944         
945         -- Typecheck the instance decls, and rules
946         -- Note that imported dictionary functions are already
947         -- in scope from the preceding tcTyClDecls
948         tcIfaceInstDecls inst_decls     `thenM` \ dfuns ->
949         tcExtendInstEnv dfuns           $
950         tcRules rule_decls              `thenM` \ rules ->
951         tcExtendRules rules             $
952     
953         getGblEnv               -- Return the environment
954    }}
955 \end{code}
956
957
958
959 %*********************************************************
960 %*                                                       *
961         mkGlobalContext: make up an interactive context
962
963         Used for initialising the lexical environment
964         of the interactive read-eval-print loop
965 %*                                                       *
966 %*********************************************************
967
968 \begin{code}
969 #ifdef GHCI
970 mkGlobalContext
971         :: HscEnv -> PersistentCompilerState
972         -> [Module]     -- Expose these modules' top-level scope
973         -> [Module]     -- Expose these modules' exports only
974         -> IO (PersistentCompilerState, Maybe GlobalRdrEnv)
975
976 mkGlobalContext hsc_env pcs toplevs exports
977   = initTc hsc_env pcs iNTERACTIVE $ do {
978
979     toplev_envs <- mappM getTopLevScope   toplevs ;
980     export_envs <- mappM getModuleExports exports ;
981     returnM (foldr plusGlobalRdrEnv emptyGlobalRdrEnv
982                    (toplev_envs ++ export_envs))
983     }
984
985 getTopLevScope :: Module -> TcRn m GlobalRdrEnv
986 getTopLevScope mod
987   = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
988          case mi_globals iface of
989                 Nothing  -> panic "getTopLevScope"
990                 Just env -> returnM env }
991
992 getModuleExports :: Module -> TcRn m GlobalRdrEnv
993 getModuleExports mod 
994   = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
995          returnM (foldl add emptyGlobalRdrEnv (mi_exports iface)) }
996   where
997     prov_fn n = NonLocalDef ImplicitImport
998     add env (mod,avails)
999         = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True prov_fn avails NoDeprecs)
1000
1001 contextDoc = text "context for compiling statements"
1002 \end{code}
1003
1004 \begin{code}
1005 getModuleContents
1006   :: HscEnv
1007   -> PersistentCompilerState    -- IN: persistent compiler state
1008   -> Module                     -- module to inspect
1009   -> Bool                       -- grab just the exports, or the whole toplev
1010   -> IO (PersistentCompilerState, Maybe [TyThing])
1011
1012 getModuleContents hsc_env pcs mod exports_only
1013  = initTc hsc_env pcs iNTERACTIVE $ do {   
1014
1015         -- Load the interface if necessary (a home module will certainly
1016         -- alraedy be loaded, but a package module might not be)
1017         iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
1018
1019         let { export_names = availsToNameSet export_avails ;
1020               export_avails = [ avail | (mn, avails) <- mi_exports iface, 
1021                                         avail <- avails ] } ;
1022
1023         all_names <- if exports_only then 
1024                         return export_names
1025                      else case mi_globals iface of {
1026                            Just rdr_env -> 
1027                                 return (get_locals rdr_env) ;
1028
1029                            Nothing -> do { addErr (noRdrEnvErr mod) ;
1030                                            return export_names } } ;
1031                                 -- Invariant; we only have (not exports_only) 
1032                                 -- for a home module so it must already be in the HIT
1033                                 -- So the Nothing case is a bug
1034
1035         env <- importSupportingDecls all_names ;
1036         setGblEnv env (mappM tcLookupGlobal (nameSetToList all_names))
1037     }
1038   where
1039         -- Grab all the things from the global env that are locally def'd
1040     get_locals rdr_env = mkNameSet [ gre_name gre
1041                                    | elts <- rdrEnvElts rdr_env, 
1042                                      gre <- elts, 
1043                                      isLocalGRE gre ]
1044         -- Make a set because a name is often in the envt in
1045         -- both qualified and unqualified forms
1046
1047 noRdrEnvErr mod = ptext SLIT("No top-level environment available for module") 
1048                   <+> quotes (ppr mod)
1049 #endif
1050 \end{code}
1051
1052 %************************************************************************
1053 %*                                                                      *
1054         Checking for 'main'
1055 %*                                                                      *
1056 %************************************************************************
1057
1058 \begin{code}
1059 checkMain 
1060   = do { ghci_mode <- getGhciMode ;
1061          tcg_env   <- getGblEnv ;
1062          check_main ghci_mode tcg_env
1063     }
1064
1065 check_main ghci_mode tcg_env
1066      -- If we are in module Main, check that 'main' is defined.
1067      -- It may be imported from another module, in which case 
1068      -- we have to drag in its.
1069      -- 
1070      -- Also form the definition
1071      --         $main = runIO main
1072      -- so we need to slurp in runIO too.
1073      --
1074      -- ToDo: We have to return the main_name separately, because it's a
1075      -- bona fide 'use', and should be recorded as such, but the others
1076      -- aren't 
1077      -- 
1078      -- Blimey: a whole page of code to do this...
1079
1080  | mod_name /= mAIN_Name
1081  = return (tcg_env, emptyFVs)
1082
1083  | not (main_RDR_Unqual `elemRdrEnv` rdr_env)
1084  = do { complain_no_main; return (tcg_env, emptyFVs) }
1085
1086  | otherwise
1087  = do {         -- Check that 'main' is in scope
1088                 -- It might be imported from another module!
1089         main_name <- lookupSrcName main_RDR_Unqual ;
1090         failIfErrsM ;
1091
1092         tcg_env <- importSupportingDecls (unitFV runIOName) ;
1093         setGblEnv tcg_env $ do {
1094         
1095         -- $main :: IO () = runIO main
1096         let { rhs = HsApp (HsVar runIOName) (HsVar main_name) } ;
1097
1098         (main_bind, top_lie) <- getLIE (
1099                 addSrcLoc (getSrcLoc main_name) $
1100                 addErrCtxt mainCtxt             $ do {
1101                 (main_expr, ty) <- tcExpr_id rhs ;
1102                 let { dollar_main_id = setIdLocalExported (mkLocalId dollarMainName ty) } ;
1103                 return (VarMonoBind dollar_main_id main_expr)
1104             }) ;
1105
1106         inst_binds <- tcSimplifyTop top_lie ;
1107
1108         (ids, binds') <- zonkTopBinds (main_bind `andMonoBinds` inst_binds) ;
1109         
1110         let { tcg_env' = tcg_env { 
1111                 tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) ids,
1112                 tcg_binds = tcg_binds tcg_env `andMonoBinds` binds' } } ;
1113
1114         return (tcg_env', unitFV main_name)
1115     }}
1116   where
1117     mod_name = moduleName (tcg_mod tcg_env) 
1118     rdr_env  = tcg_rdr_env tcg_env
1119  
1120     main_RDR_Unqual :: RdrName
1121     main_RDR_Unqual = mkUnqual varName FSLIT("main")
1122         -- Don't get a RdrName from PrelNames.mainName, because 
1123         -- nameRdrNamegets an Orig RdrName, and we want a Qual or Unqual one.  
1124         -- An Unqual one will do just fine
1125
1126     complain_no_main | ghci_mode == Interactive = return ()
1127                      | otherwise                = addErr noMainMsg
1128         -- In interactive mode, don't worry about the absence of 'main'
1129
1130     mainCtxt  = ptext SLIT("When checking the type of 'main'")
1131     noMainMsg = ptext SLIT("No 'main' defined in module Main")
1132 \end{code}
1133
1134
1135 %************************************************************************
1136 %*                                                                      *
1137                 Degugging output
1138 %*                                                                      *
1139 %************************************************************************
1140
1141 \begin{code}
1142 rnDump :: SDoc -> TcRn m ()
1143 -- Dump, with a banner, if -ddump-rn
1144 rnDump doc = dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc)
1145
1146 tcDump :: TcGblEnv -> TcRn m ()
1147 tcDump env
1148  = do { dflags <- getDOpts ;
1149
1150         -- Dump short output if -ddump-types or -ddump-tc
1151         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1152             (dumpTcRn short_dump) ;
1153
1154         -- Dump bindings if -ddump-tc
1155         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1156    }
1157   where
1158     short_dump = pprTcGblEnv env
1159     full_dump  = ppr (tcg_binds env)
1160         -- NB: foreign x-d's have undefined's in their types; 
1161         --     hence can't show the tc_fords
1162
1163 tcCoreDump mod_guts
1164  = do { dflags <- getDOpts ;
1165         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1166             (dumpTcRn (pprModGuts mod_guts)) ;
1167
1168         -- Dump bindings if -ddump-tc
1169         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1170   where
1171     full_dump = pprCoreBindings (mg_binds mod_guts)
1172
1173 -- It's unpleasant having both pprModGuts and pprModDetails here
1174 pprTcGblEnv :: TcGblEnv -> SDoc
1175 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env, 
1176                         tcg_insts    = dfun_ids, 
1177                         tcg_rules    = rules,
1178                         tcg_imports  = imports })
1179   = vcat [ ppr_types dfun_ids type_env
1180          , ppr_insts dfun_ids
1181          , vcat (map ppr rules)
1182          , ppr_gen_tycons (typeEnvTyCons type_env)
1183          , ppr (moduleEnvElts (imp_dep_mods imports))
1184          , ppr (imp_dep_pkgs imports)]
1185
1186 pprModGuts :: ModGuts -> SDoc
1187 pprModGuts (ModGuts { mg_types = type_env,
1188                       mg_rules = rules })
1189   = vcat [ ppr_types [] type_env,
1190            ppr_rules rules ]
1191
1192
1193 ppr_types :: [Var] -> TypeEnv -> SDoc
1194 ppr_types dfun_ids type_env
1195   = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1196   where
1197     ids = [id | id <- typeEnvIds type_env, want_sig id]
1198     want_sig id | opt_PprStyle_Debug = True
1199                 | otherwise          = isLocalId id && 
1200                                        isExternalName (idName id) && 
1201                                        not (id `elem` dfun_ids)
1202         -- isLocalId ignores data constructors, records selectors etc.
1203         -- The isExternalName ignores local dictionary and method bindings
1204         -- that the type checker has invented.  Top-level user-defined things 
1205         -- have External names.
1206
1207 ppr_insts :: [Var] -> SDoc
1208 ppr_insts []       = empty
1209 ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)
1210
1211 ppr_sigs :: [Var] -> SDoc
1212 ppr_sigs ids
1213         -- Print type signatures
1214         -- Convert to HsType so that we get source-language style printing
1215         -- And sort by RdrName
1216   = vcat $ map ppr_sig $ sortLt lt_sig $
1217     [ (getRdrName id, toHsType (idType id))
1218     | id <- ids ]
1219   where
1220     lt_sig (n1,_) (n2,_) = n1 < n2
1221     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
1222
1223
1224 ppr_rules :: [IdCoreRule] -> SDoc
1225 ppr_rules [] = empty
1226 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1227                       nest 4 (pprIdRules rs),
1228                       ptext SLIT("#-}")]
1229
1230 ppr_gen_tycons []  = empty
1231 ppr_gen_tycons tcs = vcat [ptext SLIT("{-# Generic type constructor details"),
1232                            vcat (map ppr_gen_tycon tcs),
1233                            ptext SLIT("#-}")
1234                      ]
1235
1236 -- x&y are now Id's, not CoreExpr's 
1237 ppr_gen_tycon tycon 
1238   | Just ep <- tyConGenInfo tycon
1239   = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
1240
1241   | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
1242
1243 ppr_ep (EP from to)
1244   = vcat [ ptext SLIT("Rep type:") <+> ppr (tcFunResultTy from_tau),
1245            ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
1246            ptext SLIT("To:")   <+> ppr (unfoldingTemplate (idUnfolding to))
1247     ]
1248   where
1249     (_,from_tau) = tcSplitForAllTys (idType from)
1250 \end{code}