[project @ 2003-10-09 11:58:39 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         mkExportEnv, getModuleContents, tcRnStmt, tcRnThing, tcRnExpr,
10 #endif
11         tcRnModule, 
12         tcTopSrcDecls,
13         tcRnIface, tcRnExtCore
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 DriverState      ( v_MainModIs, v_MainFunIs )
24 import HsSyn            ( HsModule(..), HsBinds(..), MonoBinds(..), HsExpr(..),
25                           HsGroup(..), SpliceDecl(..), HsExtCore(..),
26                           andMonoBinds
27                         )
28 import RdrHsSyn         ( RdrNameHsModule, RdrNameHsDecl, 
29                           findSplice, main_RDR_Unqual )
30
31 import PrelNames        ( runIOName, rootMainName, mAIN_Name )
32 import RdrName          ( RdrName, mkRdrUnqual, emptyGlobalRdrEnv, 
33                           plusGlobalRdrEnv )
34 import TcHsSyn          ( zonkTopDecls )
35 import TcExpr           ( tcInferRho )
36 import TcRnMonad
37 import TcType           ( tidyTopType )
38 import Inst             ( showLIE )
39 import TcBinds          ( tcTopBinds )
40 import TcDefaults       ( tcDefaults )
41 import TcEnv            ( tcExtendGlobalValEnv, tcLookupGlobal )
42 import TcRules          ( tcRules )
43 import TcForeign        ( tcForeignImports, tcForeignExports )
44 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
45 import TcIface          ( typecheckIface, tcExtCoreBindings )
46 import TcSimplify       ( tcSimplifyTop )
47 import TcTyClsDecls     ( tcTyAndClassDecls )
48 import LoadIface        ( loadOrphanModules )
49 import RnNames          ( importsFromLocalDecls, rnImports, exportsFromAvail, 
50                           reportUnusedNames )
51 import RnEnv            ( lookupSrcOcc_maybe )
52 import RnSource         ( rnSrcDecls, rnTyClDecls, checkModDeprec )
53 import PprCore          ( pprIdRules, pprCoreBindings )
54 import CoreSyn          ( IdCoreRule, bindersOfBinds )
55 import ErrUtils         ( mkDumpDoc, showPass )
56 import Id               ( mkLocalId, isLocalId, idName, idType, setIdLocalExported )
57 import Var              ( Var )
58 import Module           ( mkHomeModule, mkModuleName, moduleName, moduleEnvElts )
59 import OccName          ( mkVarOcc )
60 import Name             ( Name, isExternalName, getSrcLoc, getOccName )
61 import NameSet
62 import TyCon            ( tyConHasGenerics )
63 import Outputable
64 import HscTypes         ( ModIface, ModDetails(..), ModGuts(..),
65                           HscEnv(..), ModIface(..), ModDetails(..), 
66                           GhciMode(..), noDependencies,
67                           Deprecs( NoDeprecs ), plusDeprecs,
68                           GenAvailInfo(Avail), availsToNameSet, availName,
69                           ForeignStubs(NoStubs), TypeEnv, typeEnvTyCons, 
70                           extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
71                           emptyFixityEnv
72                         )
73 #ifdef GHCI
74 import HsSyn            ( HsStmtContext(..), 
75                           Stmt(..), Pat(VarPat), 
76                           collectStmtsBinders, mkSimpleMatch, placeHolderType )
77 import RdrHsSyn         ( RdrNameHsExpr, RdrNameStmt )
78 import RdrName          ( GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
79                           Provenance(..), ImportSpec(..),
80                           lookupLocalRdrEnv, extendLocalRdrEnv )
81 import RnHsSyn          ( RenamedStmt ) 
82 import RnSource         ( addTcgDUs )
83 import TcHsSyn          ( TypecheckedHsExpr, mkHsLet, zonkTopExpr, zonkTopBndrs )
84 import TcExpr           ( tcCheckRho )
85 import TcMType          ( zonkTcType )
86 import TcMatches        ( tcStmtsAndThen, TcStmtCtxt(..) )
87 import TcSimplify       ( tcSimplifyInteractive, tcSimplifyInfer )
88 import TcType           ( Type, mkForAllTys, mkFunTys, mkTyConApp, tyVarsOfType )
89 import TcEnv            ( tcLookupTyCon, tcLookupId )
90 import TyCon            ( DataConDetails(..) )
91 import Inst             ( tcStdSyntaxName )
92 import RnExpr           ( rnStmts, rnExpr )
93 import RnNames          ( exportsToAvails )
94 import LoadIface        ( loadSysInterface )
95 import IfaceSyn         ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..), IfaceExtName(..),
96                           tyThingToIfaceDecl )
97 import IfaceEnv         ( tcIfaceGlobal )
98 import RnEnv            ( lookupOccRn, dataTcOccs, lookupFixityRn )
99 import Id               ( Id, isImplicitId )
100 import MkId             ( unsafeCoerceId )
101 import TysWiredIn       ( mkListTy, unitTy )
102 import IdInfo           ( GlobalIdDetails(..) )
103 import SrcLoc           ( interactiveSrcLoc )
104 import Var              ( setGlobalIdDetails )
105 import Name             ( nameOccName, nameModuleName )
106 import NameEnv          ( delListFromNameEnv )
107 import PrelNames        ( iNTERACTIVE, ioTyConName, printName, monadNames, itName, returnIOName )
108 import Module           ( ModuleName, lookupModuleEnvByName )
109 import HscTypes         ( InteractiveContext(..),
110                           HomeModInfo(..), typeEnvElts, 
111                           TyThing(..), availNames, icPrintUnqual )
112 import BasicTypes       ( RecFlag(..), Fixity )
113 import Panic            ( ghcError, GhcException(..) )
114 #endif
115
116 import FastString       ( mkFastString )
117 import Util             ( sortLt )
118 \end{code}
119
120
121
122 %************************************************************************
123 %*                                                                      *
124         Typecheck and rename a module
125 %*                                                                      *
126 %************************************************************************
127
128
129 \begin{code}
130 tcRnModule :: HscEnv 
131            -> RdrNameHsModule 
132            -> IO (Maybe TcGblEnv)
133
134 tcRnModule hsc_env
135            (HsModule maybe_mod exports import_decls local_decls mod_deprec loc)
136  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
137
138    let { this_mod = case maybe_mod of
139                         Nothing  -> mkHomeModule mAIN_Name      -- 'module M where' is omitted
140                         Just mod -> mod } ;                     -- The normal case
141                 
142    initTc hsc_env this_mod $ addSrcLoc loc $
143    do {         -- Deal with imports; sets tcg_rdr_env, tcg_imports
144         (rdr_env, imports) <- rnImports import_decls ;
145         updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
146                                    tcg_imports = tcg_imports gbl `plusImportAvails` imports }) 
147                      $ do {
148         traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
149                 -- Fail if there are any errors so far
150                 -- The error printing (if needed) takes advantage 
151                 -- of the tcg_env we have now set
152         failIfErrsM ;
153
154                 -- Load any orphan-module interfaces, so that
155                 -- their rules and instance decls will be found
156         loadOrphanModules (imp_orphs imports) ;
157
158         traceRn (text "rn1a") ;
159                 -- Rename and type check the declarations
160         tcg_env <- tcRnSrcDecls local_decls ;
161         setGblEnv tcg_env               $ do {
162
163         traceRn (text "rn3") ;
164
165                 -- Process the export list
166         export_avails <- exportsFromAvail maybe_mod exports ;
167
168                 -- Get any supporting decls for the exports that have not already
169                 -- been sucked in for the declarations in the body of the module.
170                 -- (This can happen if something is imported only to be re-exported.)
171                 --
172                 -- Importing these supporting declarations is required 
173                 --      *only* to gether usage information
174                 --      (see comments with MkIface.mkImportInfo for why)
175                 -- We don't need the results, but sucking them in may side-effect
176                 -- the ExternalPackageState, apart from recording usage
177         mappM (tcLookupGlobal . availName) export_avails ;
178
179                 -- Check whether the entire module is deprecated
180                 -- This happens only once per module
181         let { mod_deprecs = checkModDeprec mod_deprec } ;
182
183                 -- Add exports and deprecations to envt
184         let { export_fvs = availsToNameSet export_avails ;
185               final_env  = tcg_env { tcg_exports = export_avails,
186                                      tcg_dus = tcg_dus tcg_env `plusDU` usesOnly export_fvs,
187                                      tcg_deprecs = tcg_deprecs tcg_env `plusDeprecs` 
188                                                    mod_deprecs }
189                 -- A module deprecation over-rides the earlier ones
190              } ;
191
192                 -- Report unused names
193         reportUnusedNames final_env ;
194
195                 -- Dump output and return
196         tcDump final_env ;
197         return final_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           -> ModIface   -- Get the decls from here
214           -> IO ModDetails
215 tcRnIface hsc_env iface
216   = initIfaceIO hsc_env (typecheckIface iface)
217 \end{code}
218
219
220 %************************************************************************
221 %*                                                                      *
222                 The interactive interface 
223 %*                                                                      *
224 %************************************************************************
225
226 \begin{code}
227 #ifdef GHCI
228 tcRnStmt :: HscEnv
229          -> InteractiveContext
230          -> RdrNameStmt
231          -> IO (Maybe (InteractiveContext, [Name], TypecheckedHsExpr))
232                 -- The returned [Name] is the same as the input except for
233                 -- ExprStmt, in which case the returned [Name] is [itName]
234                 --
235                 -- The returned TypecheckedHsExpr is of type IO [ () ],
236                 -- a list of the bound values, coerced to ().
237
238 tcRnStmt hsc_env ictxt rdr_stmt
239   = initTc hsc_env iNTERACTIVE $ 
240     setInteractiveContext ictxt $ do {
241
242     -- Rename; use CmdLineMode because tcRnStmt is only used interactively
243     ([rn_stmt], fvs) <- rnStmts DoExpr [rdr_stmt] ;
244     traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
245     failIfErrsM ;
246     
247     -- The real work is done here
248     (bound_ids, tc_expr) <- tcUserStmt rn_stmt ;
249     
250     traceTc (text "tcs 1") ;
251     let {       -- Make all the bound ids "global" ids, now that
252                 -- they're notionally top-level bindings.  This is
253                 -- important: otherwise when we come to compile an expression
254                 -- using these ids later, the byte code generator will consider
255                 -- the occurrences to be free rather than global.
256         global_ids     = map globaliseId bound_ids ;
257         globaliseId id = setGlobalIdDetails id VanillaGlobal ;
258     
259                 -- Update the interactive context
260         rn_env   = ic_rn_local_env ictxt ;
261         type_env = ic_type_env ictxt ;
262
263         bound_names = map idName global_ids ;
264         new_rn_env  = extendLocalRdrEnv rn_env bound_names ;
265
266                 -- Remove any shadowed bindings from the type_env;
267                 -- they are inaccessible but might, I suppose, cause 
268                 -- a space leak if we leave them there
269         shadowed = [ n | name <- bound_names,
270                          let rdr_name = mkRdrUnqual (nameOccName name),
271                          Just n <- [lookupLocalRdrEnv rn_env rdr_name] ] ;
272
273         filtered_type_env = delListFromNameEnv type_env shadowed ;
274         new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;
275
276         new_ic = ictxt { ic_rn_local_env = new_rn_env, 
277                          ic_type_env     = new_type_env }
278     } ;
279
280     dumpOptTcRn Opt_D_dump_tc 
281         (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
282                text "Typechecked expr" <+> ppr tc_expr]) ;
283
284     returnM (new_ic, bound_names, tc_expr)
285     }
286 \end{code}              
287
288
289 Here is the grand plan, implemented in tcUserStmt
290
291         What you type                   The IO [HValue] that hscStmt returns
292         -------------                   ------------------------------------
293         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
294                                         bindings: [x,y,...]
295
296         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
297                                         bindings: [x,y,...]
298
299         expr (of IO type)       ==>     expr >>= \ v -> return [coerce HVal v]
300           [NB: result not printed]      bindings: [it]
301           
302         expr (of non-IO type,   ==>     let v = expr in print v >> return [coerce HVal v]
303           result showable)              bindings: [it]
304
305         expr (of non-IO type, 
306           result not showable)  ==>     error
307
308
309 \begin{code}
310 ---------------------------
311 tcUserStmt :: RenamedStmt -> TcM ([Id], TypecheckedHsExpr)
312 tcUserStmt (ExprStmt expr _ loc)
313   = newUnique           `thenM` \ uniq ->
314     let 
315         fresh_it = itName uniq
316         the_bind = FunMonoBind fresh_it False 
317                         [ mkSimpleMatch [] expr placeHolderType loc ] loc
318     in
319     tryTcLIE_ (do {     -- Try this if the other fails
320                 traceTc (text "tcs 1b") ;
321                 tc_stmts [
322                     LetStmt (MonoBind the_bind [] NonRecursive),
323                     ExprStmt (HsApp (HsVar printName) (HsVar fresh_it)) 
324                              placeHolderType loc] })
325           (do {         -- Try this first 
326                 traceTc (text "tcs 1a") ;
327                 tc_stmts [BindStmt (VarPat fresh_it) expr loc] })
328
329 tcUserStmt stmt = tc_stmts [stmt]
330
331 ---------------------------
332 tc_stmts stmts
333  = do { ioTyCon <- tcLookupTyCon ioTyConName ;
334         let {
335             ret_ty    = mkListTy unitTy ;
336             io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
337
338             names = collectStmtsBinders stmts ;
339
340             stmt_ctxt = SC { sc_what = DoExpr, 
341                              sc_rhs  = check_rhs,
342                              sc_body = check_body,
343                              sc_ty   = ret_ty } ;
344
345             check_rhs rhs rhs_ty = tcCheckRho rhs  (mkTyConApp ioTyCon [rhs_ty]) ;
346             check_body body      = tcCheckRho body io_ret_ty ;
347
348                 -- mk_return builds the expression
349                 --      returnIO @ [()] [coerce () x, ..,  coerce () z]
350                 --
351                 -- Despite the inconvenience of building the type applications etc,
352                 -- this *has* to be done in type-annotated post-typecheck form
353                 -- because we are going to return a list of *polymorphic* values
354                 -- coerced to type (). If we built a *source* stmt
355                 --      return [coerce x, ..., coerce z]
356                 -- then the type checker would instantiate x..z, and we wouldn't
357                 -- get their *polymorphic* values.  (And we'd get ambiguity errs
358                 -- if they were overloaded, since they aren't applied to anything.)
359             mk_return ret_id ids = HsApp (TyApp (HsVar ret_id) [ret_ty]) 
360                                          (ExplicitList unitTy (map mk_item ids)) ;
361             mk_item id = HsApp (TyApp (HsVar unsafeCoerceId) [idType id, unitTy])
362                                (HsVar id) ;
363
364             io_ty = mkTyConApp ioTyCon []
365          } ;
366
367         -- OK, we're ready to typecheck the stmts
368         traceTc (text "tcs 2") ;
369         ((ids, tc_expr), lie) <- getLIE $ do {
370             (ids, tc_stmts) <- tcStmtsAndThen combine stmt_ctxt stmts   $ 
371                         do {
372                             -- Look up the names right in the middle,
373                             -- where they will all be in scope
374                             ids <- mappM tcLookupId names ;
375                             ret_id <- tcLookupId returnIOName ;         -- return @ IO
376                             return (ids, [ResultStmt (mk_return ret_id ids) interactiveSrcLoc]) } ;
377
378             io_ids <- mappM (tcStdSyntaxName DoOrigin io_ty) monadNames ;
379             return (ids, HsDo DoExpr tc_stmts io_ids io_ret_ty interactiveSrcLoc) 
380         } ;
381
382         -- Simplify the context right here, so that we fail
383         -- if there aren't enough instances.  Notably, when we see
384         --              e
385         -- we use recoverTc_ to try     it <- e
386         -- and then                     let it = e
387         -- It's the simplify step that rejects the first.
388         traceTc (text "tcs 3") ;
389         const_binds <- tcSimplifyInteractive lie ;
390
391         -- Build result expression and zonk it
392         let { expr = mkHsLet const_binds tc_expr } ;
393         zonked_expr <- zonkTopExpr expr ;
394         zonked_ids  <- zonkTopBndrs ids ;
395
396         return (zonked_ids, zonked_expr)
397         }
398   where
399     combine stmt (ids, stmts) = (ids, stmt:stmts)
400 \end{code}
401
402
403 tcRnExpr just finds the type of an expression
404
405 \begin{code}
406 tcRnExpr :: HscEnv
407          -> InteractiveContext
408          -> RdrNameHsExpr
409          -> IO (Maybe Type)
410 tcRnExpr hsc_env ictxt rdr_expr
411   = initTc hsc_env iNTERACTIVE $ 
412     setInteractiveContext ictxt $ do {
413
414     (rn_expr, fvs) <- rnExpr rdr_expr ;
415     failIfErrsM ;
416
417         -- Now typecheck the expression; 
418         -- it might have a rank-2 type (e.g. :t runST)
419     ((tc_expr, res_ty), lie)       <- getLIE (tcInferRho rn_expr) ;
420     ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie)  ;
421     tcSimplifyInteractive lie_top ;
422
423     let { all_expr_ty = mkForAllTys qtvs                $
424                         mkFunTys (map idType dict_ids)  $
425                         res_ty } ;
426     zonkTcType all_expr_ty
427     }
428   where
429     smpl_doc = ptext SLIT("main expression")
430 \end{code}
431
432
433 \begin{code}
434 tcRnThing :: HscEnv
435           -> InteractiveContext
436           -> RdrName
437           -> IO (Maybe [(IfaceDecl, Fixity)])
438 -- Look up a RdrName and return all the TyThings it might be
439 -- A capitalised RdrName is given to us in the DataName namespace,
440 -- but we want to treat it as *both* a data constructor 
441 -- *and* as a type or class constructor; 
442 -- hence the call to dataTcOccs, and we return up to two results
443 tcRnThing hsc_env ictxt rdr_name
444   = initTc hsc_env iNTERACTIVE $ 
445     setInteractiveContext ictxt $ do {
446
447         -- If the identifier is a constructor (begins with an
448         -- upper-case letter), then we need to consider both
449         -- constructor and type class identifiers.
450     let { rdr_names = dataTcOccs rdr_name } ;
451
452         -- results :: [(Messages, Maybe Name)]
453     results <- mapM (tryTc . lookupOccRn) rdr_names ;
454
455         -- The successful lookups will be (Just name)
456     let { (warns_s, good_names) = unzip [ (msgs, name) 
457                                         | (msgs, Just name) <- results] ;
458           errs_s = [msgs | (msgs, Nothing) <- results] } ;
459
460         -- Fail if nothing good happened, else add warnings
461     if null good_names then
462                 -- No lookup succeeded, so
463                 -- pick the first error message and report it
464                 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
465                 --       while the other is "X is not in scope", 
466                 --       we definitely want the former; but we might pick the latter
467         do { addMessages (head errs_s) ; failM }
468       else                      -- Add deprecation warnings
469         mapM_ addMessages warns_s ;
470         
471         -- And lookup up the entities
472     mapM do_one good_names
473     }
474   where
475     do_one name = do { thing <- tcLookupGlobal name
476                      ; fixity <- lookupFixityRn name
477                      ; return (toIfaceDecl ictxt thing, fixity) }
478
479 toIfaceDecl :: InteractiveContext -> TyThing -> IfaceDecl
480 toIfaceDecl ictxt thing
481   = tyThingToIfaceDecl True {- Discard IdInfo -} ext_nm thing
482   where
483     unqual = icPrintUnqual ictxt
484     ext_nm n | unqual n  = LocalTop (nameOccName n)     -- What a hack
485              | otherwise = ExtPkg (nameModuleName n) (nameOccName n)
486 \end{code}
487
488
489 \begin{code}
490 setInteractiveContext :: InteractiveContext -> TcRn a -> TcRn a
491 setInteractiveContext icxt thing_inside 
492   = traceTc (text "setIC" <+> ppr (ic_type_env icxt))   `thenM_`
493     (updGblEnv (\env -> env {tcg_rdr_env  = ic_rn_gbl_env icxt,
494                              tcg_type_env = ic_type_env   icxt}) $
495      updLclEnv (\env -> env {tcl_rdr = ic_rn_local_env icxt})   $
496                thing_inside)
497 #endif /* GHCI */
498 \end{code}
499
500 %************************************************************************
501 %*                                                                      *
502         Type-checking external-core modules
503 %*                                                                      *
504 %************************************************************************
505
506 \begin{code}
507 tcRnExtCore :: HscEnv 
508             -> HsExtCore RdrName
509             -> IO (Maybe ModGuts)
510         -- Nothing => some error occurred 
511
512 tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
513         -- The decls are IfaceDecls; all names are original names
514  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
515
516    initTc hsc_env this_mod $ do {
517
518         -- Deal with the type declarations; first bring their stuff
519         -- into scope, then rname them, then type check them
520    (rdr_env, imports) <- importsFromLocalDecls $
521         HsGroup { hs_tyclds = decls, hs_valds = EmptyBinds, hs_fords = [] } ;
522                 -- Rather clumsy; lots of unused fields
523
524    updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv` tcg_rdr_env gbl,
525                             tcg_imports = imports `plusImportAvails` tcg_imports gbl }) 
526                   $ do {
527
528    rn_decls <- rnTyClDecls decls ;
529    failIfErrsM ;
530
531         -- Dump trace of renaming part
532    rnDump (ppr rn_decls) ;
533
534         -- Typecheck them all together so that
535         -- any mutually recursive types are done right
536    tcg_env <- checkNoErrs (tcTyAndClassDecls rn_decls) ;
537         -- Make the new type env available to stuff slurped from interface files
538
539    setGblEnv tcg_env $ do {
540    
541         -- Now the core bindings
542    core_binds <- initIfaceExtCore (tcExtCoreBindings this_mod src_binds) ;
543
544         -- Wrap up
545    let {
546         bndrs      = bindersOfBinds core_binds ;
547         my_exports = map (Avail . idName) bndrs ;
548                 -- ToDo: export the data types also?
549
550         final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
551
552         mod_guts = ModGuts {    mg_module   = this_mod,
553                                 mg_usages   = [],               -- ToDo: compute usage
554                                 mg_dir_imps = [],               -- ??
555                                 mg_deps     = noDependencies,   -- ??
556                                 mg_exports  = my_exports,
557                                 mg_types    = final_type_env,
558                                 mg_insts    = tcg_insts tcg_env,
559                                 mg_rules    = [],
560                                 mg_binds    = core_binds,
561
562                                 -- Stubs
563                                 mg_rdr_env  = emptyGlobalRdrEnv,
564                                 mg_fix_env  = emptyFixityEnv,
565                                 mg_deprecs  = NoDeprecs,
566                                 mg_foreign  = NoStubs
567                     } } ;
568
569    tcCoreDump mod_guts ;
570
571    return mod_guts
572    }}}}
573 \end{code}
574
575
576 %************************************************************************
577 %*                                                                      *
578         Type-checking the top level of a module
579 %*                                                                      *
580 %************************************************************************
581
582 \begin{code}
583 tcRnSrcDecls :: [RdrNameHsDecl] -> TcM TcGblEnv
584         -- Returns the variables free in the decls
585         -- Reason: solely to report unused imports and bindings
586 tcRnSrcDecls decls
587  = do {         -- Do all the declarations
588         (tc_envs, lie) <- getLIE (tc_rn_src_decls decls) ;
589
590              -- tcSimplifyTop deals with constant or ambiguous InstIds.  
591              -- How could there be ambiguous ones?  They can only arise if a
592              -- top-level decl falls under the monomorphism
593              -- restriction, and no subsequent decl instantiates its
594              -- type.  (Usually, ambiguous type variables are resolved
595              -- during the generalisation step.)
596         traceTc (text "Tc8") ;
597         inst_binds <- setEnvs tc_envs (tcSimplifyTop lie) ;
598                 -- Setting the global env exposes the instances to tcSimplifyTop
599                 -- Setting the local env exposes the local Ids to tcSimplifyTop, 
600                 -- so that we get better error messages (monomorphism restriction)
601
602             -- Backsubstitution.  This must be done last.
603             -- Even tcSimplifyTop may do some unification.
604         traceTc (text "Tc9") ;
605         let { (tcg_env, _) = tc_envs ;
606               TcGblEnv { tcg_type_env = type_env, tcg_binds = binds, 
607                          tcg_rules = rules, tcg_fords = fords } = tcg_env } ;
608
609         (bind_ids, binds', fords', rules') <- zonkTopDecls (binds `andMonoBinds` inst_binds)
610                                                            rules fords ;
611
612         let { final_type_env = extendTypeEnvWithIds type_env bind_ids } ;
613
614         -- Make the new type env available to stuff slurped from interface files
615         writeMutVar (tcg_type_env_var tcg_env) final_type_env ;
616
617         return (tcg_env { tcg_type_env = final_type_env,
618                           tcg_binds = binds', tcg_rules = rules', tcg_fords = fords' }) 
619    }
620
621 tc_rn_src_decls :: [RdrNameHsDecl] -> TcM (TcGblEnv, TcLclEnv)
622 -- Loops around dealing with each top level inter-splice group 
623 -- in turn, until it's dealt with the entire module
624 tc_rn_src_decls ds
625  = do { let { (first_group, group_tail) = findSplice ds } ;
626                 -- If ds is [] we get ([], Nothing)
627
628         -- Type check the decls up to, but not including, the first splice
629         tc_envs@(tcg_env,tcl_env) <- tcRnGroup first_group ;
630
631         -- Bale out if errors; for example, error recovery when checking
632         -- the RHS of 'main' can mean that 'main' is not in the envt for 
633         -- the subsequent checkMain test
634         failIfErrsM ;
635
636         setEnvs tc_envs $
637
638         -- If there is no splice, we're nearly done
639         case group_tail of {
640            Nothing -> do {      -- Last thing: check for `main'
641                            tcg_env <- checkMain ;
642                            return (tcg_env, tcl_env) 
643                       } ;
644
645         -- If there's a splice, we must carry on
646            Just (SpliceDecl splice_expr splice_loc, rest_ds) -> do {
647 #ifndef GHCI
648         failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
649 #else
650
651         -- Rename the splice expression, and get its supporting decls
652         (rn_splice_expr, splice_fvs) <- addSrcLoc splice_loc $
653                                         rnExpr splice_expr ;
654         -- Execute the splice
655         spliced_decls <- tcSpliceDecls rn_splice_expr ;
656
657         -- Glue them on the front of the remaining decls and loop
658         setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
659         tc_rn_src_decls (spliced_decls ++ rest_ds)
660 #endif /* GHCI */
661     }}}
662 \end{code}
663
664
665 %************************************************************************
666 %*                                                                      *
667         Type-checking the top level of a module
668 %*                                                                      *
669 %************************************************************************
670
671 tcRnGroup takes a bunch of top-level source-code declarations, and
672  * renames them
673  * gets supporting declarations from interface files
674  * typechecks them
675  * zonks them
676  * and augments the TcGblEnv with the results
677
678 In Template Haskell it may be called repeatedly for each group of
679 declarations.  It expects there to be an incoming TcGblEnv in the
680 monad; it augments it and returns the new TcGblEnv.
681
682 \begin{code}
683 tcRnGroup :: HsGroup RdrName -> TcM (TcGblEnv, TcLclEnv)
684         -- Returns the variables free in the decls, for unused-binding reporting
685 tcRnGroup decls
686  = do {         -- Rename the declarations
687         (tcg_env, rn_decls) <- rnTopSrcDecls decls ;
688         setGblEnv tcg_env $ do {
689
690                 -- Typecheck the declarations
691         tcTopSrcDecls rn_decls 
692   }}
693
694 ------------------------------------------------
695 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
696 rnTopSrcDecls group
697  = do {         -- Bring top level binders into scope
698         (rdr_env, imports) <- importsFromLocalDecls group ;
699         updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv` tcg_rdr_env gbl,
700                                  tcg_imports = imports `plusImportAvails` tcg_imports gbl }) 
701                   $ do {
702
703         failIfErrsM ;   -- No point in continuing if (say) we have duplicate declarations
704
705                 -- Rename the source decls
706         (tcg_env, rn_decls) <- rnSrcDecls group ;
707         failIfErrsM ;
708
709                 -- Dump trace of renaming part
710         rnDump (ppr rn_decls) ;
711
712         return (tcg_env, rn_decls)
713    }}
714
715 ------------------------------------------------
716 tcTopSrcDecls :: HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
717 tcTopSrcDecls
718         (HsGroup { hs_tyclds = tycl_decls, 
719                    hs_instds = inst_decls,
720                    hs_fords  = foreign_decls,
721                    hs_defds  = default_decls,
722                    hs_ruleds = rule_decls,
723                    hs_valds  = val_binds })
724  = do {         -- Type-check the type and class decls, and all imported decls
725                 -- The latter come in via tycl_decls
726         traceTc (text "Tc2") ;
727
728         tcg_env <- checkNoErrs (tcTyAndClassDecls tycl_decls) ;
729         -- tcTyAndClassDecls recovers internally, but if anything gave rise to
730         -- an error we'd better stop now, to avoid a cascade
731         
732         -- Make these type and class decls available to stuff slurped from interface files
733         writeMutVar (tcg_type_env_var tcg_env) (tcg_type_env tcg_env) ;
734
735
736         setGblEnv tcg_env       $ do {
737                 -- Source-language instances, including derivings,
738                 -- and import the supporting declarations
739         traceTc (text "Tc3") ;
740         (tcg_env, inst_infos, deriv_binds) <- tcInstDecls1 tycl_decls inst_decls ;
741         setGblEnv tcg_env       $ do {
742
743                 -- Foreign import declarations next.  No zonking necessary
744                 -- here; we can tuck them straight into the global environment.
745         traceTc (text "Tc4") ;
746         (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
747         tcExtendGlobalValEnv fi_ids     $ do {
748
749                 -- Default declarations
750         traceTc (text "Tc4a") ;
751         default_tys <- tcDefaults default_decls ;
752         updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
753         
754                 -- Value declarations next
755                 -- We also typecheck any extra binds that came out 
756                 -- of the "deriving" process (deriv_binds)
757         traceTc (text "Tc5") ;
758         (tc_val_binds, lcl_env) <- tcTopBinds (val_binds `ThenBinds` deriv_binds) ;
759         setLclTypeEnv lcl_env   $ do {
760
761                 -- Second pass over class and instance declarations, 
762         traceTc (text "Tc6") ;
763         (tcl_env, inst_binds) <- tcInstDecls2 tycl_decls inst_infos ;
764         showLIE (text "after instDecls2") ;
765
766                 -- Foreign exports
767                 -- They need to be zonked, so we return them
768         traceTc (text "Tc7") ;
769         (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
770
771                 -- Rules
772         rules <- tcRules rule_decls ;
773
774                 -- Wrap up
775         traceTc (text "Tc7a") ;
776         tcg_env <- getGblEnv ;
777         let { all_binds = tc_val_binds   `AndMonoBinds`
778                           inst_binds     `AndMonoBinds`
779                           foe_binds  ;
780
781                 -- Extend the GblEnv with the (as yet un-zonked) 
782                 -- bindings, rules, foreign decls
783               tcg_env' = tcg_env {  tcg_binds = tcg_binds tcg_env `andMonoBinds` all_binds,
784                                     tcg_rules = tcg_rules tcg_env ++ rules,
785                                     tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
786         return (tcg_env', lcl_env)
787     }}}}}}
788 \end{code}
789
790
791 %*********************************************************
792 %*                                                       *
793         mkGlobalContext: make up an interactive context
794
795         Used for initialising the lexical environment
796         of the interactive read-eval-print loop
797 %*                                                       *
798 %*********************************************************
799
800 \begin{code}
801 #ifdef GHCI
802 mkExportEnv :: HscEnv -> [ModuleName]   -- Expose these modules' exports only
803             -> IO GlobalRdrEnv
804
805 mkExportEnv hsc_env exports
806   = initIfaceIO hsc_env $ do {
807     export_envs <- mappM getModuleExports exports ;
808     returnM (foldr plusGlobalRdrEnv emptyGlobalRdrEnv export_envs)
809     }
810
811 getModuleExports :: ModuleName -> IfG GlobalRdrEnv
812 getModuleExports mod 
813   = do  { iface <- load_iface mod
814         ; avails <- exportsToAvails (mi_exports iface)
815         ; let { gres = [ GRE  { gre_name = name, gre_prov = vanillaProv mod,
816                                 gre_deprec = mi_dep_fn iface name }
817                         | avail <- avails, name <- availNames avail ] }
818         ; returnM (mkGlobalRdrEnv gres) }
819
820 vanillaProv :: ModuleName -> Provenance
821 -- We're building a GlobalRdrEnv as if the user imported
822 -- all the specified modules into the global interactive module
823 vanillaProv mod = Imported [ImportSpec mod mod False interactiveSrcLoc] False
824 \end{code}
825
826 \begin{code}
827 getModuleContents
828   :: HscEnv
829   -> InteractiveContext
830   -> ModuleName                 -- Module to inspect
831   -> Bool                       -- Grab just the exports, or the whole toplev
832   -> IO [IfaceDecl]
833
834 getModuleContents hsc_env ictxt mod exports_only
835  = initIfaceIO hsc_env (get_mod_contents exports_only)
836  where
837    get_mod_contents exports_only
838       | not exports_only        -- We want the whole top-level type env
839                           -- so it had better be a home module
840       = do { hpt <- getHpt
841            ; case lookupModuleEnvByName hpt mod of
842                Just mod_info -> return (map (toIfaceDecl ictxt) $
843                                         filter wantToSee $
844                                         typeEnvElts $
845                                         md_types (hm_details mod_info))
846                Nothing -> ghcError (ProgramError (showSDoc (noRdrEnvErr mod)))
847                           -- This is a system error; the module should be in the HPT
848            }
849   
850       | otherwise               -- Want the exports only
851       = do { iface <- load_iface mod
852            ; avails <- exportsToAvails (mi_exports iface)
853            ; mappM get_decl avails
854         }
855
856    get_decl avail 
857         = do { thing <- tcIfaceGlobal (availName avail)
858              ; return (filter_decl (availOccs avail) (toIfaceDecl ictxt thing)) }
859
860 ---------------------
861 filter_decl occs decl@(IfaceClass {ifSigs = sigs})
862   = decl { ifSigs = filter (keep_sig occs) sigs }
863 filter_decl occs decl@(IfaceData {ifCons = DataCons cons})
864   = decl { ifCons = DataCons (filter (keep_con occs) cons) }
865 filter_decl occs decl
866   = decl
867
868 keep_sig occs (IfaceClassOp occ _ _)       = occ `elem` occs
869 keep_con occs (IfaceConDecl occ _ _ _ _ _) = occ `elem` occs
870
871 availOccs avail = map nameOccName (availNames avail)
872
873 wantToSee (AnId id)    = not (isImplicitId id)
874 wantToSee (ADataCon _) = False  -- They'll come via their TyCon
875 wantToSee _            = True
876
877 ---------------------
878 load_iface mod = loadSysInterface (text "context for compiling statements") mod
879
880 ---------------------
881 noRdrEnvErr mod = ptext SLIT("No top-level environment available for module") 
882                   <+> quotes (ppr mod)
883 #endif
884 \end{code}
885
886 %************************************************************************
887 %*                                                                      *
888         Checking for 'main'
889 %*                                                                      *
890 %************************************************************************
891
892 \begin{code}
893 checkMain 
894   = do { ghci_mode <- getGhciMode ;
895          tcg_env   <- getGblEnv ;
896
897          mb_main_mod <- readMutVar v_MainModIs ;
898          mb_main_fn  <- readMutVar v_MainFunIs ;
899          let { main_mod = case mb_main_mod of {
900                                 Just mod -> mkModuleName mod ;
901                                 Nothing  -> mAIN_Name } ;
902                 main_fn  = case mb_main_fn of {
903                                 Just fn -> mkRdrUnqual (mkVarOcc (mkFastString fn)) ;
904                                 Nothing -> main_RDR_Unqual } } ;
905         
906          check_main ghci_mode tcg_env main_mod main_fn
907     }
908
909
910 check_main ghci_mode tcg_env main_mod main_fn
911      -- If we are in module Main, check that 'main' is defined.
912      -- It may be imported from another module!
913      --
914      -- ToDo: We have to return the main_name separately, because it's a
915      -- bona fide 'use', and should be recorded as such, but the others
916      -- aren't 
917      -- 
918      -- Blimey: a whole page of code to do this...
919  | mod_name /= main_mod
920  = return tcg_env
921
922  | otherwise
923  = addErrCtxt mainCtxt                  $
924    do   { mb_main <- lookupSrcOcc_maybe main_fn
925                 -- Check that 'main' is in scope
926                 -- It might be imported from another module!
927         ; case mb_main of {
928              Nothing -> do { complain_no_main   
929                            ; return tcg_env } ;
930              Just main_name -> do
931         { let { rhs = HsApp (HsVar runIOName) (HsVar main_name) }
932                         -- :Main.main :: IO () = runIO main 
933
934         ; (main_expr, ty) <- addSrcLoc (getSrcLoc main_name)    $
935                              tcInferRho rhs
936
937         ; let { root_main_id = setIdLocalExported (mkLocalId rootMainName ty) ;
938                 main_bind    = VarMonoBind root_main_id main_expr }
939
940         ; return (tcg_env { tcg_binds = tcg_binds tcg_env 
941                                         `andMonoBinds` main_bind,
942                             tcg_dus   = tcg_dus tcg_env
943                                         `plusDU` usesOnly (unitFV main_name)
944                  }) 
945     }}}
946   where
947     mod_name = moduleName (tcg_mod tcg_env) 
948  
949     complain_no_main | ghci_mode == Interactive = return ()
950                      | otherwise                = failWithTc noMainMsg
951         -- In interactive mode, don't worry about the absence of 'main'
952         -- In other modes, fail altogether, so that we don't go on
953         -- and complain a second time when processing the export list.
954
955     mainCtxt  = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
956     noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn) 
957                 <+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
958 \end{code}
959
960
961 %************************************************************************
962 %*                                                                      *
963                 Degugging output
964 %*                                                                      *
965 %************************************************************************
966
967 \begin{code}
968 rnDump :: SDoc -> TcRn ()
969 -- Dump, with a banner, if -ddump-rn
970 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
971
972 tcDump :: TcGblEnv -> TcRn ()
973 tcDump env
974  = do { dflags <- getDOpts ;
975
976         -- Dump short output if -ddump-types or -ddump-tc
977         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
978             (dumpTcRn short_dump) ;
979
980         -- Dump bindings if -ddump-tc
981         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
982    }
983   where
984     short_dump = pprTcGblEnv env
985     full_dump  = ppr (tcg_binds env)
986         -- NB: foreign x-d's have undefined's in their types; 
987         --     hence can't show the tc_fords
988
989 tcCoreDump mod_guts
990  = do { dflags <- getDOpts ;
991         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
992             (dumpTcRn (pprModGuts mod_guts)) ;
993
994         -- Dump bindings if -ddump-tc
995         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
996   where
997     full_dump = pprCoreBindings (mg_binds mod_guts)
998
999 -- It's unpleasant having both pprModGuts and pprModDetails here
1000 pprTcGblEnv :: TcGblEnv -> SDoc
1001 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env, 
1002                         tcg_insts    = dfun_ids, 
1003                         tcg_rules    = rules,
1004                         tcg_imports  = imports })
1005   = vcat [ ppr_types dfun_ids type_env
1006          , ppr_insts dfun_ids
1007          , vcat (map ppr rules)
1008          , ppr_gen_tycons (typeEnvTyCons type_env)
1009          , ptext SLIT("Dependent modules:") <+> ppr (moduleEnvElts (imp_dep_mods imports))
1010          , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1011
1012 pprModGuts :: ModGuts -> SDoc
1013 pprModGuts (ModGuts { mg_types = type_env,
1014                       mg_rules = rules })
1015   = vcat [ ppr_types [] type_env,
1016            ppr_rules rules ]
1017
1018
1019 ppr_types :: [Var] -> TypeEnv -> SDoc
1020 ppr_types dfun_ids type_env
1021   = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1022   where
1023     ids = [id | id <- typeEnvIds type_env, want_sig id]
1024     want_sig id | opt_PprStyle_Debug = True
1025                 | otherwise          = isLocalId id && 
1026                                        isExternalName (idName id) && 
1027                                        not (id `elem` dfun_ids)
1028         -- isLocalId ignores data constructors, records selectors etc.
1029         -- The isExternalName ignores local dictionary and method bindings
1030         -- that the type checker has invented.  Top-level user-defined things 
1031         -- have External names.
1032
1033 ppr_insts :: [Var] -> SDoc
1034 ppr_insts []       = empty
1035 ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)
1036
1037 ppr_sigs :: [Var] -> SDoc
1038 ppr_sigs ids
1039         -- Print type signatures; sort by OccName 
1040   = vcat (map ppr_sig (sortLt lt_sig ids))
1041   where
1042     lt_sig id1 id2 = getOccName id1 < getOccName id2
1043     ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1044
1045 ppr_rules :: [IdCoreRule] -> SDoc
1046 ppr_rules [] = empty
1047 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1048                       nest 4 (pprIdRules rs),
1049                       ptext SLIT("#-}")]
1050
1051 ppr_gen_tycons []  = empty
1052 ppr_gen_tycons tcs = vcat [ptext SLIT("Tycons with generics:"),
1053                            nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]
1054 \end{code}