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