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