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