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