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