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