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