Do not filter the type envt after each GHCi stmt
[ghc-hetmet.git] / 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         tcRnStmt, tcRnExpr, tcRnType,
10         tcRnLookupRdrName,
11         tcRnLookupName,
12         tcRnGetInfo,
13         getModuleExports, 
14 #endif
15         tcRnModule, 
16         tcTopSrcDecls,
17         tcRnExtCore
18     ) where
19
20 #include "HsVersions.h"
21
22 import IO
23 #ifdef GHCI
24 import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
25 #endif
26
27 import DynFlags         ( DynFlag(..), DynFlags(..), dopt, GhcMode(..) )
28 import StaticFlags      ( opt_PprStyle_Debug )
29 import HsSyn            ( HsModule(..), HsExtCore(..), HsGroup(..), LHsDecl,
30                           SpliceDecl(..), HsBind(..), LHsBinds,
31                           emptyRdrGroup, emptyRnGroup, appendGroups, plusHsValBinds,
32                           nlHsApp, nlHsVar, pprLHsBinds, HaddockModInfo(..) )
33 import RdrHsSyn         ( findSplice )
34
35 import PrelNames        ( runMainIOName, rootMainKey, rOOT_MAIN, mAIN,
36                           main_RDR_Unqual )
37 import RdrName          ( RdrName, mkRdrUnqual, emptyGlobalRdrEnv )
38 import TcHsSyn          ( zonkTopDecls )
39 import TcExpr           ( tcInferRho )
40 import TcRnMonad
41 import TcType           ( tidyTopType, tcEqType )
42 import Inst             ( showLIE )
43 import InstEnv          ( extendInstEnvList, Instance, pprInstances,
44                           instanceDFunId ) 
45 import FamInstEnv       ( FamInst, pprFamInsts )
46 import TcBinds          ( tcTopBinds, tcHsBootSigs )
47 import TcDefaults       ( tcDefaults )
48 import TcEnv            ( tcExtendGlobalValEnv, iDFunId )
49 import TcRules          ( tcRules )
50 import TcForeign        ( tcForeignImports, tcForeignExports )
51 import TcInstDcls       ( tcInstDecls1, tcInstDecls2 )
52 import TcIface          ( tcExtCoreBindings, tcHiBootIface )
53 import MkIface          ( tyThingToIfaceDecl )
54 import IfaceSyn         ( checkBootDecl, IfaceExtName(..) )
55 import TcSimplify       ( tcSimplifyTop )
56 import TcTyClsDecls     ( tcTyAndClassDecls )
57 import LoadIface        ( loadOrphanModules )
58 import RnNames          ( importsFromLocalDecls, rnImports, rnExports,
59                           mkRdrEnvAndImports, mkExportNameSet,
60                           reportUnusedNames, reportDeprecations )
61 import RnEnv            ( lookupSrcOcc_maybe )
62 import RnSource         ( rnSrcDecls, rnTyClDecls, checkModDeprec )
63 import RnHsDoc          ( rnMbHsDoc )
64 import PprCore          ( pprRules, pprCoreBindings )
65 import CoreSyn          ( CoreRule, bindersOfBinds )
66 import ErrUtils         ( Messages, mkDumpDoc, showPass )
67 import Id               ( Id, mkExportedLocalId, isLocalId, idName, idType )
68 import Var              ( Var )
69 import Module
70 import UniqFM           ( elemUFM, eltsUFM )
71 import OccName          ( mkVarOccFS, plusOccEnv )
72 import Name             ( Name, NamedThing(..), isExternalName, getSrcLoc, isWiredInName,
73                           nameModule, nameOccName, isImplicitName, mkExternalName )
74 import NameSet
75 import TyCon            ( tyConHasGenerics )
76 import SrcLoc           ( srcLocSpan, Located(..), noLoc )
77 import DriverPhases     ( HscSource(..), isHsBoot )
78 import HscTypes         ( ModGuts(..), ModDetails(..), emptyModDetails,
79                           HscEnv(..), ExternalPackageState(..),
80                           IsBootInterface, noDependencies, 
81                           Deprecs( NoDeprecs ), plusDeprecs,
82                           ForeignStubs(NoStubs), 
83                           TypeEnv, lookupTypeEnv, hptInstances, 
84                           extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons, typeEnvElts,
85                           emptyFixityEnv
86                         )
87 import Outputable
88
89 #ifdef GHCI
90 import HsSyn            ( HsStmtContext(..), Stmt(..), HsExpr(..), 
91                           HsLocalBinds(..), HsValBinds(..),
92                           LStmt, LHsExpr, LHsType, mkMatch, emptyLocalBinds,
93                           collectLStmtsBinders, collectLStmtBinders, nlVarPat,
94                           mkFunBind, placeHolderType, noSyntaxExpr, nlHsTyApp )
95 import RdrName          ( GlobalRdrElt(..), globalRdrEnvElts,
96                           unQualOK, lookupLocalRdrEnv, extendLocalRdrEnv )
97 import RnSource         ( addTcgDUs )
98 import TcHsSyn          ( mkHsDictLet, zonkTopLExpr, zonkTopBndrs )
99 import TcHsType         ( kcHsType )
100 import TcMType          ( zonkTcType, zonkQuantifiedTyVar )
101 import TcMatches        ( tcStmts, tcDoStmt )
102 import TcSimplify       ( tcSimplifyInteractive, tcSimplifyInfer )
103 import TcGadt           ( emptyRefinement )
104 import TcType           ( Type, mkForAllTys, mkFunTys, mkTyConApp, tyVarsOfType, isTauTy,
105                           isUnLiftedType, tyClsNamesOfDFunHead, tyClsNamesOfType, isUnitTy )
106 import TcEnv            ( tcLookupTyCon, tcLookupId, tcLookupGlobal )
107 import TypeRep          ( TyThing(..) )
108 import RnTypes          ( rnLHsType )
109 import Inst             ( tcGetInstEnvs )
110 import InstEnv          ( classInstances, instEnvElts )
111 import RnExpr           ( rnStmts, rnLExpr )
112 import LoadIface        ( loadSysInterface )
113 import IfaceEnv         ( ifaceExportNames )
114 import RnEnv            ( lookupOccRn, dataTcOccs, lookupFixityRn )
115 import Id               ( setIdType )
116 import MkId             ( unsafeCoerceId )
117 import TyCon            ( tyConName )
118 import TysWiredIn       ( mkListTy, unitTy )
119 import IdInfo           ( GlobalIdDetails(..) )
120 import {- Kind parts of -} Type         ( Kind )
121 import Var              ( globaliseId )
122 import Name             ( isBuiltInSyntax, isInternalName )
123 import OccName          ( isTcOcc )
124 import NameEnv          ( delListFromNameEnv )
125 import PrelNames        ( iNTERACTIVE, ioTyConName, printName, itName, 
126                           bindIOName, thenIOName, returnIOName )
127 import HscTypes         ( InteractiveContext(..),
128                           ModIface(..), icPrintUnqual,
129                           Dependencies(..) )
130 import BasicTypes       ( Fixity, RecFlag(..) )
131 import SrcLoc           ( unLoc )
132 import Data.Maybe       ( isNothing )
133 #endif
134
135 import FastString       ( mkFastString )
136 import Util             ( sortLe )
137 import Bag              ( unionBags, snocBag, emptyBag, unitBag, unionManyBags )
138
139 import Control.Monad    ( unless )
140 import Data.Maybe       ( isJust )
141 \end{code}
142
143
144
145 %************************************************************************
146 %*                                                                      *
147         Typecheck and rename a module
148 %*                                                                      *
149 %************************************************************************
150
151
152 \begin{code}
153 tcRnModule :: HscEnv 
154            -> HscSource
155            -> Bool              -- True <=> save renamed syntax
156            -> Located (HsModule RdrName)
157            -> IO (Messages, Maybe TcGblEnv)
158
159 tcRnModule hsc_env hsc_src save_rn_syntax
160          (L loc (HsModule maybe_mod export_ies 
161                           import_decls local_decls mod_deprec _ module_info maybe_doc))
162  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
163
164    let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
165          this_mod = case maybe_mod of
166                         Nothing  -> mAIN        -- 'module M where' is omitted
167                         Just (L _ mod) -> mkModule this_pkg mod } ;
168                                                 -- The normal case
169                 
170    initTc hsc_env hsc_src this_mod $ 
171    setSrcSpan loc $
172    do {
173                 -- Deal with imports;
174         rn_imports <- rnImports import_decls ;
175         (rdr_env, imports) <- mkRdrEnvAndImports rn_imports ;
176
177         let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
178             ; dep_mods = imp_dep_mods imports
179
180                 -- We want instance declarations from all home-package
181                 -- modules below this one, including boot modules, except
182                 -- ourselves.  The 'except ourselves' is so that we don't
183                 -- get the instances from this module's hs-boot file
184             ; want_instances :: ModuleName -> Bool
185             ; want_instances mod = mod `elemUFM` dep_mods
186                                    && mod /= moduleName this_mod
187             ; home_insts = hptInstances hsc_env want_instances
188             } ;
189
190                 -- Record boot-file info in the EPS, so that it's 
191                 -- visible to loadHiBootInterface in tcRnSrcDecls,
192                 -- and any other incrementally-performed imports
193         updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
194
195                 -- Update the gbl env
196         updGblEnv ( \ gbl -> 
197                 gbl { tcg_rdr_env  = plusOccEnv (tcg_rdr_env gbl) rdr_env,
198                       tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
199                       tcg_imports  = tcg_imports gbl `plusImportAvails` imports,
200                       tcg_rn_imports = if save_rn_syntax then
201                                          Just rn_imports
202                                        else
203                                          Nothing,
204                       tcg_rn_decls = if save_rn_syntax then
205                                         Just emptyRnGroup
206                                      else
207                                         Nothing })
208                 $ do {
209
210         traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
211                 -- Fail if there are any errors so far
212                 -- The error printing (if needed) takes advantage 
213                 -- of the tcg_env we have now set
214         failIfErrsM ;
215
216                 -- Load any orphan-module interfaces, so that
217                 -- their rules and instance decls will be found
218         loadOrphanModules (imp_orphs imports) ;
219
220         traceRn (text "rn1a") ;
221                 -- Rename and type check the declarations
222         tcg_env <- if isHsBoot hsc_src then
223                         tcRnHsBootDecls local_decls
224                    else 
225                         tcRnSrcDecls local_decls ;
226         setGblEnv tcg_env               $ do {
227
228         traceRn (text "rn3") ;
229
230                 -- Report the use of any deprecated things
231                 -- We do this before processsing the export list so
232                 -- that we don't bleat about re-exporting a deprecated
233                 -- thing (especially via 'module Foo' export item)
234                 -- Only uses in the body of the module are complained about
235         reportDeprecations (hsc_dflags hsc_env) tcg_env ;
236
237                 -- Process the export list
238         rn_exports <- rnExports export_ies ;
239                  
240                 -- Rename the Haddock documentation header 
241         rn_module_doc <- rnMbHsDoc maybe_doc ;
242
243                 -- Rename the Haddock module info 
244         rn_description <- rnMbHsDoc (hmi_description module_info) ;
245         let { rn_module_info = module_info { hmi_description = rn_description } } ;
246
247         let { liftM2' fn a b = do a' <- a; b' <- b; return (fn a' b') } ;
248         exports <- mkExportNameSet (isJust maybe_mod) 
249                                    (liftM2' (,) rn_exports export_ies) ;
250
251                 -- Check whether the entire module is deprecated
252                 -- This happens only once per module
253         let { mod_deprecs = checkModDeprec mod_deprec } ;
254
255                 -- Add exports and deprecations to envt
256         let { final_env  = tcg_env { tcg_exports = exports,
257                                      tcg_rn_exports = if save_rn_syntax then
258                                                          rn_exports
259                                                       else Nothing,
260                                      tcg_dus = tcg_dus tcg_env `plusDU` usesOnly exports,
261                                      tcg_deprecs = tcg_deprecs tcg_env `plusDeprecs` 
262                                                    mod_deprecs,
263                                      tcg_doc = rn_module_doc, 
264                                      tcg_hmi = rn_module_info
265                                   }
266                 -- A module deprecation over-rides the earlier ones
267              } ;
268
269                 -- Report unused names
270         reportUnusedNames export_ies final_env ;
271
272                 -- Dump output and return
273         tcDump final_env ;
274         return final_env
275     }}}}
276 \end{code}
277
278
279 %************************************************************************
280 %*                                                                      *
281         Type-checking external-core modules
282 %*                                                                      *
283 %************************************************************************
284
285 \begin{code}
286 tcRnExtCore :: HscEnv 
287             -> HsExtCore RdrName
288             -> IO (Messages, Maybe ModGuts)
289         -- Nothing => some error occurred 
290
291 tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
292         -- The decls are IfaceDecls; all names are original names
293  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
294
295    initTc hsc_env ExtCoreFile this_mod $ do {
296
297    let { ldecls  = map noLoc decls } ;
298
299         -- Deal with the type declarations; first bring their stuff
300         -- into scope, then rname them, then type check them
301    tcg_env  <- importsFromLocalDecls (mkFakeGroup ldecls) ;
302
303    setGblEnv tcg_env $ do {
304
305    rn_decls <- rnTyClDecls ldecls ;
306    failIfErrsM ;
307
308         -- Dump trace of renaming part
309    rnDump (ppr rn_decls) ;
310
311         -- Typecheck them all together so that
312         -- any mutually recursive types are done right
313    tcg_env <- checkNoErrs (tcTyAndClassDecls emptyModDetails rn_decls) ;
314         -- Make the new type env available to stuff slurped from interface files
315
316    setGblEnv tcg_env $ do {
317    
318         -- Now the core bindings
319    core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
320
321         -- Wrap up
322    let {
323         bndrs      = bindersOfBinds core_binds ;
324         my_exports = mkNameSet (map idName bndrs) ;
325                 -- ToDo: export the data types also?
326
327         final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
328
329         mod_guts = ModGuts {    mg_module    = this_mod,
330                                 mg_boot      = False,
331                                 mg_usages    = [],              -- ToDo: compute usage
332                                 mg_dir_imps  = [],              -- ??
333                                 mg_deps      = noDependencies,  -- ??
334                                 mg_exports   = my_exports,
335                                 mg_types     = final_type_env,
336                                 mg_insts     = tcg_insts tcg_env,
337                                 mg_fam_insts = tcg_fam_insts tcg_env,
338                                 mg_rules     = [],
339                                 mg_binds     = core_binds,
340
341                                 -- Stubs
342                                 mg_rdr_env   = emptyGlobalRdrEnv,
343                                 mg_fix_env   = emptyFixityEnv,
344                                 mg_deprecs   = NoDeprecs,
345                                 mg_foreign   = NoStubs
346                     } } ;
347
348    tcCoreDump mod_guts ;
349
350    return mod_guts
351    }}}}
352
353 mkFakeGroup decls -- Rather clumsy; lots of unused fields
354   = emptyRdrGroup { hs_tyclds = decls }
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360         Type-checking the top level of a module
361 %*                                                                      *
362 %************************************************************************
363
364 \begin{code}
365 tcRnSrcDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
366         -- Returns the variables free in the decls
367         -- Reason: solely to report unused imports and bindings
368 tcRnSrcDecls decls
369  = do {         -- Load the hi-boot interface for this module, if any
370                 -- We do this now so that the boot_names can be passed
371                 -- to tcTyAndClassDecls, because the boot_names are 
372                 -- automatically considered to be loop breakers
373         mod <- getModule ;
374         boot_iface <- tcHiBootIface mod ;
375
376                 -- Do all the declarations
377         (tc_envs, lie) <- getLIE (tc_rn_src_decls boot_iface decls) ;
378
379              -- tcSimplifyTop deals with constant or ambiguous InstIds.  
380              -- How could there be ambiguous ones?  They can only arise if a
381              -- top-level decl falls under the monomorphism
382              -- restriction, and no subsequent decl instantiates its
383              -- type.  (Usually, ambiguous type variables are resolved
384              -- during the generalisation step.)
385         traceTc (text "Tc8") ;
386         inst_binds <- setEnvs tc_envs (tcSimplifyTop lie) ;
387                 -- Setting the global env exposes the instances to tcSimplifyTop
388                 -- Setting the local env exposes the local Ids to tcSimplifyTop, 
389                 -- so that we get better error messages (monomorphism restriction)
390
391             -- Backsubstitution.  This must be done last.
392             -- Even tcSimplifyTop may do some unification.
393         traceTc (text "Tc9") ;
394         let { (tcg_env, _) = tc_envs ;
395               TcGblEnv { tcg_type_env = type_env, tcg_binds = binds, 
396                          tcg_rules = rules, tcg_fords = fords } = tcg_env } ;
397
398         (bind_ids, binds', fords', rules') <- zonkTopDecls (binds `unionBags` inst_binds)
399                                                            rules fords ;
400
401         let { final_type_env = extendTypeEnvWithIds type_env bind_ids
402             ; tcg_env' = tcg_env { tcg_type_env = final_type_env,
403                                    tcg_binds = binds',
404                                    tcg_rules = rules', 
405                                    tcg_fords = fords' } } ;
406
407         -- Make the new type env available to stuff slurped from interface files
408         writeMutVar (tcg_type_env_var tcg_env) final_type_env ;
409
410         -- Compare the hi-boot iface (if any) with the real thing
411         dfun_binds <- checkHiBootIface tcg_env' boot_iface ;
412
413         return (tcg_env' { tcg_binds = tcg_binds tcg_env' `unionBags` dfun_binds }) 
414    }
415
416 tc_rn_src_decls :: ModDetails -> [LHsDecl RdrName] -> TcM (TcGblEnv, TcLclEnv)
417 -- Loops around dealing with each top level inter-splice group 
418 -- in turn, until it's dealt with the entire module
419 tc_rn_src_decls boot_details ds
420  = do { let { (first_group, group_tail) = findSplice ds } ;
421                 -- If ds is [] we get ([], Nothing)
422
423         -- Type check the decls up to, but not including, the first splice
424         tc_envs@(tcg_env,tcl_env) <- tcRnGroup boot_details first_group ;
425
426         -- Bale out if errors; for example, error recovery when checking
427         -- the RHS of 'main' can mean that 'main' is not in the envt for 
428         -- the subsequent checkMain test
429         failIfErrsM ;
430
431         setEnvs tc_envs $
432
433         -- If there is no splice, we're nearly done
434         case group_tail of {
435            Nothing -> do {      -- Last thing: check for `main'
436                            tcg_env <- checkMain ;
437                            return (tcg_env, tcl_env) 
438                       } ;
439
440         -- If there's a splice, we must carry on
441            Just (SpliceDecl splice_expr, rest_ds) -> do {
442 #ifndef GHCI
443         failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
444 #else
445
446         -- Rename the splice expression, and get its supporting decls
447         (rn_splice_expr, splice_fvs) <- rnLExpr splice_expr ;
448         failIfErrsM ;   -- Don't typecheck if renaming failed
449         rnDump (ppr rn_splice_expr) ;
450
451         -- Execute the splice
452         spliced_decls <- tcSpliceDecls rn_splice_expr ;
453
454         -- Glue them on the front of the remaining decls and loop
455         setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
456         tc_rn_src_decls boot_details (spliced_decls ++ rest_ds)
457 #endif /* GHCI */
458     }}}
459 \end{code}
460
461 %************************************************************************
462 %*                                                                      *
463         Compiling hs-boot source files, and
464         comparing the hi-boot interface with the real thing
465 %*                                                                      *
466 %************************************************************************
467
468 \begin{code}
469 tcRnHsBootDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
470 tcRnHsBootDecls decls
471    = do { let { (first_group, group_tail) = findSplice decls }
472
473         ; case group_tail of
474              Just stuff -> spliceInHsBootErr stuff
475              Nothing    -> return ()
476
477                 -- Rename the declarations
478         ; (tcg_env, rn_group) <- rnTopSrcDecls first_group
479         ; setGblEnv tcg_env $ do {
480
481         -- Todo: check no foreign decls, no rules, no default decls
482
483                 -- Typecheck type/class decls
484         ; traceTc (text "Tc2")
485         ; let tycl_decls = hs_tyclds rn_group
486         ; tcg_env <- checkNoErrs (tcTyAndClassDecls emptyModDetails tycl_decls)
487         ; setGblEnv tcg_env     $ do {
488
489                 -- Typecheck instance decls
490         ; traceTc (text "Tc3")
491         ; (tcg_env, inst_infos, _binds) 
492             <- tcInstDecls1 tycl_decls (hs_instds rn_group) (hs_derivds rn_group)
493         ; setGblEnv tcg_env     $ do {
494
495                 -- Typecheck value declarations
496         ; traceTc (text "Tc5") 
497         ; val_ids <- tcHsBootSigs (hs_valds rn_group)
498
499                 -- Wrap up
500                 -- No simplification or zonking to do
501         ; traceTc (text "Tc7a")
502         ; gbl_env <- getGblEnv 
503         
504                 -- Make the final type-env
505                 -- Include the dfun_ids so that their type sigs get
506                 -- are written into the interface file
507         ; let { type_env0 = tcg_type_env gbl_env
508               ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
509               ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids 
510               ; dfun_ids = map iDFunId inst_infos }
511         ; return (gbl_env { tcg_type_env = type_env2 }) 
512    }}}}
513
514 spliceInHsBootErr (SpliceDecl (L loc _), _)
515   = addErrAt loc (ptext SLIT("Splices are not allowed in hs-boot files"))
516 \end{code}
517
518 Once we've typechecked the body of the module, we want to compare what
519 we've found (gathered in a TypeEnv) with the hi-boot details (if any).
520
521 \begin{code}
522 checkHiBootIface :: TcGblEnv -> ModDetails -> TcM (LHsBinds Id)
523 -- Compare the hi-boot file for this module (if there is one)
524 -- with the type environment we've just come up with
525 -- In the common case where there is no hi-boot file, the list
526 -- of boot_names is empty.
527 --
528 -- The bindings we return give bindings for the dfuns defined in the
529 -- hs-boot file, such as        $fbEqT = $fEqT
530
531 checkHiBootIface
532         (TcGblEnv { tcg_insts = local_insts, tcg_fam_insts = local_fam_insts,
533                     tcg_type_env = local_type_env })
534         (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
535                       md_types = boot_type_env })
536   = do  { traceTc (text "checkHiBootIface" <+> (ppr boot_type_env $$ ppr boot_insts)) ;
537         ; mapM_ check_one (typeEnvElts boot_type_env)
538         ; dfun_binds <- mapM check_inst boot_insts
539         ; unless (null boot_fam_insts) $
540             panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
541                    "instances in boot files yet...")
542             -- FIXME: Why?  The actual comparison is not hard, but what would
543             --        be the equivalent to the dfun bindings returned for class
544             --        instances?  We can't easily equate tycons...
545         ; return (unionManyBags dfun_binds) }
546   where
547     check_one boot_thing
548       | no_check name
549       = return ()       
550       | Just real_thing <- lookupTypeEnv local_type_env name
551       = do { let boot_decl = tyThingToIfaceDecl ext_nm boot_thing
552                  real_decl = tyThingToIfaceDecl ext_nm real_thing
553            ; checkTc (checkBootDecl boot_decl real_decl)
554                      (bootMisMatch boot_thing boot_decl real_decl) }
555                 -- The easiest way to check compatibility is to convert to
556                 -- iface syntax, where we already have good comparison functions
557       | otherwise
558       = addErrTc (missingBootThing boot_thing)
559       where
560         name = getName boot_thing
561
562     ext_nm name = ExtPkg (nameModule name) (nameOccName name)
563         -- Just enough to compare; no versions etc needed
564
565     no_check name = isWiredInName name  -- No checking for wired-in names.  In particular,
566                                         -- 'error' is handled by a rather gross hack
567                                         -- (see comments in GHC.Err.hs-boot)
568                   || name `elem` dfun_names
569                   || isImplicitName name        -- Has a parent, which we'll check
570
571     dfun_names = map getName boot_insts
572
573     check_inst boot_inst
574         = case [dfun | inst <- local_insts, 
575                        let dfun = instanceDFunId inst,
576                        idType dfun `tcEqType` boot_inst_ty ] of
577             [] -> do { addErrTc (instMisMatch boot_inst); return emptyBag }
578             (dfun:_) -> return (unitBag $ noLoc $ VarBind local_boot_dfun (nlHsVar dfun))
579         where
580           boot_dfun = instanceDFunId boot_inst
581           boot_inst_ty = idType boot_dfun
582           local_boot_dfun = mkExportedLocalId (idName boot_dfun) boot_inst_ty
583
584 ----------------
585 missingBootThing thing
586   = ppr thing <+> ptext SLIT("is defined in the hs-boot file, but not in the module")
587 bootMisMatch thing boot_decl real_decl
588   = vcat [ppr thing <+> ptext SLIT("has conflicting definitions in the module and its hs-boot file"),
589           ptext SLIT("Decl") <+> ppr real_decl,
590           ptext SLIT("Boot file:") <+> ppr boot_decl]
591 instMisMatch inst
592   = hang (ppr inst)
593        2 (ptext SLIT("is defined in the hs-boot file, but not in the module"))
594 \end{code}
595
596
597 %************************************************************************
598 %*                                                                      *
599         Type-checking the top level of a module
600 %*                                                                      *
601 %************************************************************************
602
603 tcRnGroup takes a bunch of top-level source-code declarations, and
604  * renames them
605  * gets supporting declarations from interface files
606  * typechecks them
607  * zonks them
608  * and augments the TcGblEnv with the results
609
610 In Template Haskell it may be called repeatedly for each group of
611 declarations.  It expects there to be an incoming TcGblEnv in the
612 monad; it augments it and returns the new TcGblEnv.
613
614 \begin{code}
615 tcRnGroup :: ModDetails -> HsGroup RdrName -> TcM (TcGblEnv, TcLclEnv)
616         -- Returns the variables free in the decls, for unused-binding reporting
617 tcRnGroup boot_details decls
618  = do {         -- Rename the declarations
619         (tcg_env, rn_decls) <- rnTopSrcDecls decls ;
620         setGblEnv tcg_env $ do {
621
622                 -- Typecheck the declarations
623         tcTopSrcDecls boot_details rn_decls 
624   }}
625
626 ------------------------------------------------
627 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
628 rnTopSrcDecls group
629  = do {         -- Bring top level binders into scope
630         tcg_env <- importsFromLocalDecls group ;
631         setGblEnv tcg_env $ do {
632
633         failIfErrsM ;   -- No point in continuing if (say) we have duplicate declarations
634
635                 -- Rename the source decls
636         (tcg_env, rn_decls) <- rnSrcDecls group ;
637         failIfErrsM ;
638
639                 -- save the renamed syntax, if we want it
640         let { tcg_env'
641                 | Just grp <- tcg_rn_decls tcg_env
642                   = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
643                 | otherwise
644                    = tcg_env };
645
646                 -- Dump trace of renaming part
647         rnDump (ppr rn_decls) ;
648
649         return (tcg_env', rn_decls)
650    }}
651
652 ------------------------------------------------
653 tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
654 tcTopSrcDecls boot_details
655         (HsGroup { hs_tyclds = tycl_decls, 
656                    hs_instds = inst_decls,
657                    hs_derivds = deriv_decls,
658                    hs_fords  = foreign_decls,
659                    hs_defds  = default_decls,
660                    hs_ruleds = rule_decls,
661                    hs_valds  = val_binds })
662  = do {         -- Type-check the type and class decls, and all imported decls
663                 -- The latter come in via tycl_decls
664         traceTc (text "Tc2") ;
665
666         tcg_env <- checkNoErrs (tcTyAndClassDecls boot_details tycl_decls) ;
667         -- tcTyAndClassDecls recovers internally, but if anything gave rise to
668         -- an error we'd better stop now, to avoid a cascade
669         
670         -- Make these type and class decls available to stuff slurped from interface files
671         writeMutVar (tcg_type_env_var tcg_env) (tcg_type_env tcg_env) ;
672
673
674         setGblEnv tcg_env       $ do {
675                 -- Source-language instances, including derivings,
676                 -- and import the supporting declarations
677         traceTc (text "Tc3") ;
678         (tcg_env, inst_infos, deriv_binds) 
679             <- tcInstDecls1 tycl_decls inst_decls deriv_decls;
680         setGblEnv tcg_env       $ do {
681
682                 -- Foreign import declarations next.  No zonking necessary
683                 -- here; we can tuck them straight into the global environment.
684         traceTc (text "Tc4") ;
685         (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
686         tcExtendGlobalValEnv fi_ids     $ do {
687
688                 -- Default declarations
689         traceTc (text "Tc4a") ;
690         default_tys <- tcDefaults default_decls ;
691         updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
692         
693                 -- Value declarations next
694                 -- We also typecheck any extra binds that came out 
695                 -- of the "deriving" process (deriv_binds)
696         traceTc (text "Tc5") ;
697         (tc_val_binds, tcl_env) <- tcTopBinds (val_binds `plusHsValBinds` deriv_binds) ;
698         setLclTypeEnv tcl_env   $ do {
699
700                 -- Second pass over class and instance declarations, 
701         traceTc (text "Tc6") ;
702         (inst_binds, tcl_env) <- tcInstDecls2 tycl_decls inst_infos ;
703         showLIE (text "after instDecls2") ;
704
705                 -- Foreign exports
706                 -- They need to be zonked, so we return them
707         traceTc (text "Tc7") ;
708         (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
709
710                 -- Rules
711         rules <- tcRules rule_decls ;
712
713                 -- Wrap up
714         traceTc (text "Tc7a") ;
715         tcg_env <- getGblEnv ;
716         let { all_binds = tc_val_binds   `unionBags`
717                           inst_binds     `unionBags`
718                           foe_binds  ;
719
720                 -- Extend the GblEnv with the (as yet un-zonked) 
721                 -- bindings, rules, foreign decls
722               tcg_env' = tcg_env {  tcg_binds = tcg_binds tcg_env `unionBags` all_binds,
723                                     tcg_rules = tcg_rules tcg_env ++ rules,
724                                     tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
725         return (tcg_env', tcl_env)
726     }}}}}}
727 \end{code}
728
729
730 %************************************************************************
731 %*                                                                      *
732         Checking for 'main'
733 %*                                                                      *
734 %************************************************************************
735
736 \begin{code}
737 checkMain :: TcM TcGblEnv
738 -- If we are in module Main, check that 'main' is defined.
739 checkMain 
740   = do { ghc_mode <- getGhcMode ;
741          tcg_env   <- getGblEnv ;
742          dflags    <- getDOpts ;
743          let { main_mod = mainModIs dflags ;
744                main_fn  = case mainFunIs dflags of {
745                                 Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn)) ;
746                                 Nothing -> main_RDR_Unqual } } ;
747         
748          check_main ghc_mode tcg_env main_mod main_fn
749     }
750
751
752 check_main ghc_mode tcg_env main_mod main_fn
753  | mod /= main_mod
754  = traceTc (text "checkMain not" <+> ppr main_mod <+> ppr mod) >>
755    return tcg_env
756
757  | otherwise
758  = addErrCtxt mainCtxt                  $
759    do   { mb_main <- lookupSrcOcc_maybe main_fn
760                 -- Check that 'main' is in scope
761                 -- It might be imported from another module!
762         ; case mb_main of {
763              Nothing -> do { traceTc (text "checkMain fail" <+> ppr main_mod <+> ppr main_fn)
764                            ; complain_no_main   
765                            ; return tcg_env } ;
766              Just main_name -> do
767         { traceTc (text "checkMain found" <+> ppr main_mod <+> ppr main_fn)
768         ; let { rhs = nlHsApp (nlHsVar runMainIOName) (nlHsVar main_name) }
769                         -- :Main.main :: IO () = runMainIO main 
770
771         ; (main_expr, ty) <- setSrcSpan (srcLocSpan (getSrcLoc main_name)) $
772                              tcInferRho rhs
773
774         -- The function that the RTS invokes is always :Main.main,
775         -- which we call root_main_id.  
776         -- (Because GHC allows the user to have a module not called 
777         -- Main as the main module, we can't rely on the main function
778         -- being called "Main.main".  That's why root_main_id has a fixed
779         -- module ":Main".)
780         -- We also make root_main_id an implicit Id, by making main_name
781         -- its parent (hence (Just main_name)).  That has the effect
782         -- of preventing its type and unfolding from getting out into
783         -- the interface file. Otherwise we can end up with two defns
784         -- for 'main' in the interface file!
785
786         ; let { root_main_name =  mkExternalName rootMainKey rOOT_MAIN 
787                                    (mkVarOccFS FSLIT("main")) 
788                                    (Just main_name) (getSrcLoc main_name)
789               ; root_main_id = mkExportedLocalId root_main_name ty
790               ; main_bind    = noLoc (VarBind root_main_id main_expr) }
791
792         ; return (tcg_env { tcg_binds = tcg_binds tcg_env 
793                                         `snocBag` main_bind,
794                             tcg_dus   = tcg_dus tcg_env
795                                         `plusDU` usesOnly (unitFV main_name)
796                         -- Record the use of 'main', so that we don't 
797                         -- complain about it being defined but not used
798                  }) 
799     }}}
800   where
801     mod = tcg_mod tcg_env
802  
803     complain_no_main | ghc_mode == Interactive = return ()
804                      | otherwise                = failWithTc noMainMsg
805         -- In interactive mode, don't worry about the absence of 'main'
806         -- In other modes, fail altogether, so that we don't go on
807         -- and complain a second time when processing the export list.
808
809     mainCtxt  = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
810     noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn) 
811                 <+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
812 \end{code}
813
814 %*********************************************************
815 %*                                                       *
816                 GHCi stuff
817 %*                                                       *
818 %*********************************************************
819
820 \begin{code}
821 #ifdef GHCI
822 setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
823 setInteractiveContext hsc_env icxt thing_inside 
824   = let 
825         -- Initialise the tcg_inst_env with instances 
826         -- from all home modules.  This mimics the more selective
827         -- call to hptInstances in tcRnModule
828         dfuns = hptInstances hsc_env (\mod -> True)
829     in
830     updGblEnv (\env -> env { 
831         tcg_rdr_env  = ic_rn_gbl_env icxt,
832         tcg_type_env = ic_type_env   icxt,
833         tcg_inst_env = extendInstEnvList (tcg_inst_env env) dfuns }) $
834
835     updLclEnv (\env -> env { tcl_rdr = ic_rn_local_env icxt })  $
836
837     do  { traceTc (text "setIC" <+> ppr (ic_type_env icxt))
838         ; thing_inside }
839 \end{code}
840
841
842 \begin{code}
843 tcRnStmt :: HscEnv
844          -> InteractiveContext
845          -> LStmt RdrName
846          -> IO (Maybe (InteractiveContext, [Name], LHsExpr Id))
847                 -- The returned [Name] is the same as the input except for
848                 -- ExprStmt, in which case the returned [Name] is [itName]
849                 --
850                 -- The returned TypecheckedHsExpr is of type IO [ () ],
851                 -- a list of the bound values, coerced to ().
852
853 tcRnStmt hsc_env ictxt rdr_stmt
854   = initTcPrintErrors hsc_env iNTERACTIVE $ 
855     setInteractiveContext hsc_env ictxt $ do {
856
857     -- Rename; use CmdLineMode because tcRnStmt is only used interactively
858     (([rn_stmt], _), fvs) <- rnStmts DoExpr [rdr_stmt] (return ((), emptyFVs)) ;
859     traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
860     failIfErrsM ;
861     
862     -- The real work is done here
863     (bound_ids, tc_expr) <- mkPlan rn_stmt ;
864     zonked_expr <- zonkTopLExpr tc_expr ;
865     zonked_ids  <- zonkTopBndrs bound_ids ;
866     
867         -- None of the Ids should be of unboxed type, because we
868         -- cast them all to HValues in the end!
869     mappM bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
870
871     traceTc (text "tcs 1") ;
872     let {       -- (a) Make all the bound ids "global" ids, now that
873                 --     they're notionally top-level bindings.  This is
874                 --     important: otherwise when we come to compile an expression
875                 --     using these ids later, the byte code generator will consider
876                 --     the occurrences to be free rather than global.
877                 -- 
878                 -- (b) Tidy their types; this is important, because :info may
879                 --     ask to look at them, and :info expects the things it looks
880                 --     up to have tidy types
881         global_ids = map globaliseAndTidy zonked_ids ;
882     
883                 -- Update the interactive context
884         rn_env   = ic_rn_local_env ictxt ;
885         type_env = ic_type_env ictxt ;
886
887         bound_names = map idName global_ids ;
888         new_rn_env  = extendLocalRdrEnv rn_env bound_names ;
889
890 {- ---------------------------------------------
891    At one stage I removed any shadowed bindings from the type_env;
892    they are inaccessible but might, I suppose, cause a space leak if we leave them there.
893    However, with Template Haskell they aren't necessarily inaccessible.  Consider this
894    GHCi session
895          Prelude> let f n = n * 2 :: Int
896          Prelude> fName <- runQ [| f |]
897          Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
898          14
899          Prelude> let f n = n * 3 :: Int
900          Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
901    In the last line we use 'fName', which resolves to the *first* 'f'
902    in scope. If we delete it from the type env, GHCi crashes because
903    it doesn't expect that.
904  
905    Hence this code is commented out
906
907         shadowed = [ n | name <- bound_names,
908                          let rdr_name = mkRdrUnqual (nameOccName name),
909                          Just n <- [lookupLocalRdrEnv rn_env rdr_name] ] ;
910         filtered_type_env = delListFromNameEnv type_env shadowed ;
911 -------------------------------------------------- -}
912
913         new_type_env = extendTypeEnvWithIds type_env global_ids ;
914         new_ic = ictxt { ic_rn_local_env = new_rn_env, 
915                          ic_type_env     = new_type_env }
916     } ;
917
918     dumpOptTcRn Opt_D_dump_tc 
919         (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
920                text "Typechecked expr" <+> ppr zonked_expr]) ;
921
922     returnM (new_ic, bound_names, zonked_expr)
923     }
924   where
925     bad_unboxed id = addErr (sep [ptext SLIT("GHCi can't bind a variable of unlifted type:"),
926                                   nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
927
928 globaliseAndTidy :: Id -> Id
929 globaliseAndTidy id
930 -- Give the Id a Global Name, and tidy its type
931   = setIdType (globaliseId VanillaGlobal id) tidy_type
932   where
933     tidy_type = tidyTopType (idType id)
934 \end{code}
935
936 Here is the grand plan, implemented in tcUserStmt
937
938         What you type                   The IO [HValue] that hscStmt returns
939         -------------                   ------------------------------------
940         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
941                                         bindings: [x,y,...]
942
943         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
944                                         bindings: [x,y,...]
945
946         expr (of IO type)       ==>     expr >>= \ it -> return [coerce HVal it]
947           [NB: result not printed]      bindings: [it]
948           
949         expr (of non-IO type,   ==>     let it = expr in print it >> return [coerce HVal it]
950           result showable)              bindings: [it]
951
952         expr (of non-IO type, 
953           result not showable)  ==>     error
954
955
956 \begin{code}
957 ---------------------------
958 type PlanResult = ([Id], LHsExpr Id)
959 type Plan = TcM PlanResult
960
961 runPlans :: [Plan] -> TcM PlanResult
962 -- Try the plans in order.  If one fails (by raising an exn), try the next.
963 -- If one succeeds, take it.
964 runPlans []     = panic "runPlans"
965 runPlans [p]    = p
966 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
967
968 --------------------
969 mkPlan :: LStmt Name -> TcM PlanResult
970 mkPlan (L loc (ExprStmt expr _ _))      -- An expression typed at the prompt 
971   = do  { uniq <- newUnique             -- is treated very specially
972         ; let fresh_it  = itName uniq
973               the_bind  = L loc $ mkFunBind (L loc fresh_it) matches
974               matches   = [mkMatch [] expr emptyLocalBinds]
975               let_stmt  = L loc $ LetStmt (HsValBinds (ValBindsOut [(NonRecursive,unitBag the_bind)] []))
976               bind_stmt = L loc $ BindStmt (nlVarPat fresh_it) expr
977                                            (HsVar bindIOName) noSyntaxExpr 
978               print_it  = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar fresh_it))
979                                            (HsVar thenIOName) placeHolderType
980
981         -- The plans are:
982         --      [it <- e; print it]     but not if it::()
983         --      [it <- e]               
984         --      [let it = e; print it]  
985         ; runPlans [    -- Plan A
986                     do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
987                        ; it_ty <- zonkTcType (idType it_id)
988                        ; ifM (isUnitTy it_ty) failM
989                        ; return stuff },
990
991                         -- Plan B; a naked bind statment
992                     tcGhciStmts [bind_stmt],    
993
994                         -- Plan C; check that the let-binding is typeable all by itself.
995                         -- If not, fail; if so, try to print it.
996                         -- The two-step process avoids getting two errors: one from
997                         -- the expression itself, and one from the 'print it' part
998                         -- This two-step story is very clunky, alas
999                     do { checkNoErrs (tcGhciStmts [let_stmt]) 
1000                                 --- checkNoErrs defeats the error recovery of let-bindings
1001                        ; tcGhciStmts [let_stmt, print_it] }
1002           ]}
1003
1004 mkPlan stmt@(L loc (BindStmt {}))
1005   | [L _ v] <- collectLStmtBinders stmt         -- One binder, for a bind stmt 
1006   = do  { let print_v  = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
1007                                            (HsVar thenIOName) placeHolderType
1008
1009         ; print_bind_result <- doptM Opt_PrintBindResult
1010         ; let print_plan = do
1011                   { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
1012                   ; v_ty <- zonkTcType (idType v_id)
1013                   ; ifM (isUnitTy v_ty || not (isTauTy v_ty)) failM
1014                   ; return stuff }
1015
1016         -- The plans are:
1017         --      [stmt; print v]         but not if v::()
1018         --      [stmt]
1019         ; runPlans ((if print_bind_result then [print_plan] else []) ++
1020                     [tcGhciStmts [stmt]])
1021         }
1022
1023 mkPlan stmt
1024   = tcGhciStmts [stmt]
1025
1026 ---------------------------
1027 tcGhciStmts :: [LStmt Name] -> TcM PlanResult
1028 tcGhciStmts stmts
1029  = do { ioTyCon <- tcLookupTyCon ioTyConName ;
1030         ret_id  <- tcLookupId returnIOName ;            -- return @ IO
1031         let {
1032             io_ty     = mkTyConApp ioTyCon [] ;
1033             ret_ty    = mkListTy unitTy ;
1034             io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
1035             tc_io_stmts stmts = tcStmts DoExpr (tcDoStmt io_ty) stmts 
1036                                         (emptyRefinement, io_ret_ty) ;
1037
1038             names = map unLoc (collectLStmtsBinders stmts) ;
1039
1040                 -- mk_return builds the expression
1041                 --      returnIO @ [()] [coerce () x, ..,  coerce () z]
1042                 --
1043                 -- Despite the inconvenience of building the type applications etc,
1044                 -- this *has* to be done in type-annotated post-typecheck form
1045                 -- because we are going to return a list of *polymorphic* values
1046                 -- coerced to type (). If we built a *source* stmt
1047                 --      return [coerce x, ..., coerce z]
1048                 -- then the type checker would instantiate x..z, and we wouldn't
1049                 -- get their *polymorphic* values.  (And we'd get ambiguity errs
1050                 -- if they were overloaded, since they aren't applied to anything.)
1051             mk_return ids = nlHsApp (nlHsTyApp ret_id [ret_ty]) 
1052                                     (noLoc $ ExplicitList unitTy (map mk_item ids)) ;
1053             mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
1054                                  (nlHsVar id) 
1055          } ;
1056
1057         -- OK, we're ready to typecheck the stmts
1058         traceTc (text "tcs 2") ;
1059         ((tc_stmts, ids), lie) <- getLIE $ tc_io_stmts stmts $ \ _ ->
1060                                            mappM tcLookupId names ;
1061                                         -- Look up the names right in the middle,
1062                                         -- where they will all be in scope
1063
1064         -- Simplify the context
1065         const_binds <- checkNoErrs (tcSimplifyInteractive lie) ;
1066                 -- checkNoErrs ensures that the plan fails if context redn fails
1067
1068         return (ids, mkHsDictLet const_binds $
1069                      noLoc (HsDo DoExpr tc_stmts (mk_return ids) io_ret_ty))
1070     }
1071 \end{code}
1072
1073
1074 tcRnExpr just finds the type of an expression
1075
1076 \begin{code}
1077 tcRnExpr :: HscEnv
1078          -> InteractiveContext
1079          -> LHsExpr RdrName
1080          -> IO (Maybe Type)
1081 tcRnExpr hsc_env ictxt rdr_expr
1082   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1083     setInteractiveContext hsc_env ictxt $ do {
1084
1085     (rn_expr, fvs) <- rnLExpr rdr_expr ;
1086     failIfErrsM ;
1087
1088         -- Now typecheck the expression; 
1089         -- it might have a rank-2 type (e.g. :t runST)
1090     ((tc_expr, res_ty), lie)       <- getLIE (tcInferRho rn_expr) ;
1091     ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie)  ;
1092     tcSimplifyInteractive lie_top ;
1093     qtvs' <- mappM zonkQuantifiedTyVar qtvs ;
1094
1095     let { all_expr_ty = mkForAllTys qtvs' $
1096                         mkFunTys (map idType dict_ids)  $
1097                         res_ty } ;
1098     zonkTcType all_expr_ty
1099     }
1100   where
1101     smpl_doc = ptext SLIT("main expression")
1102 \end{code}
1103
1104 tcRnType just finds the kind of a type
1105
1106 \begin{code}
1107 tcRnType :: HscEnv
1108          -> InteractiveContext
1109          -> LHsType RdrName
1110          -> IO (Maybe Kind)
1111 tcRnType hsc_env ictxt rdr_type
1112   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1113     setInteractiveContext hsc_env ictxt $ do {
1114
1115     rn_type <- rnLHsType doc rdr_type ;
1116     failIfErrsM ;
1117
1118         -- Now kind-check the type
1119     (ty', kind) <- kcHsType rn_type ;
1120     return kind
1121     }
1122   where
1123     doc = ptext SLIT("In GHCi input")
1124
1125 #endif /* GHCi */
1126 \end{code}
1127
1128
1129 %************************************************************************
1130 %*                                                                      *
1131         More GHCi stuff, to do with browsing and getting info
1132 %*                                                                      *
1133 %************************************************************************
1134
1135 \begin{code}
1136 #ifdef GHCI
1137 -- ASSUMES that the module is either in the HomePackageTable or is
1138 -- a package module with an interface on disk.  If neither of these is
1139 -- true, then the result will be an error indicating the interface
1140 -- could not be found.
1141 getModuleExports :: HscEnv -> Module -> IO (Messages, Maybe NameSet)
1142 getModuleExports hsc_env mod
1143   = initTc hsc_env HsSrcFile iNTERACTIVE (tcGetModuleExports mod)
1144
1145 tcGetModuleExports :: Module -> TcM NameSet
1146 tcGetModuleExports mod = do
1147   let doc = ptext SLIT("context for compiling statements")
1148   iface <- initIfaceTcRn $ loadSysInterface doc mod
1149   loadOrphanModules (dep_orphs (mi_deps iface))
1150                 -- Load any orphan-module interfaces,
1151                 -- so their instances are visible
1152   ifaceExportNames (mi_exports iface)
1153
1154 tcRnLookupRdrName :: HscEnv -> RdrName -> IO (Maybe [Name])
1155 tcRnLookupRdrName hsc_env rdr_name 
1156   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1157     setInteractiveContext hsc_env (hsc_IC hsc_env) $ 
1158     lookup_rdr_name rdr_name
1159
1160 lookup_rdr_name rdr_name = do {
1161         -- If the identifier is a constructor (begins with an
1162         -- upper-case letter), then we need to consider both
1163         -- constructor and type class identifiers.
1164     let { rdr_names = dataTcOccs rdr_name } ;
1165
1166         -- results :: [Either Messages Name]
1167     results <- mapM (tryTcErrs . lookupOccRn) rdr_names ;
1168
1169     traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)]);
1170         -- The successful lookups will be (Just name)
1171     let { (warns_s, good_names) = unzip [ (msgs, name) 
1172                                         | (msgs, Just name) <- results] ;
1173           errs_s = [msgs | (msgs, Nothing) <- results] } ;
1174
1175         -- Fail if nothing good happened, else add warnings
1176     if null good_names then
1177                 -- No lookup succeeded, so
1178                 -- pick the first error message and report it
1179                 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
1180                 --       while the other is "X is not in scope", 
1181                 --       we definitely want the former; but we might pick the latter
1182         do { addMessages (head errs_s) ; failM }
1183       else                      -- Add deprecation warnings
1184         mapM_ addMessages warns_s ;
1185     
1186     return good_names
1187  }
1188
1189
1190 tcRnLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
1191 tcRnLookupName hsc_env name
1192   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1193     setInteractiveContext hsc_env (hsc_IC hsc_env) $
1194     tcLookupGlobal name
1195
1196
1197 tcRnGetInfo :: HscEnv
1198             -> Name
1199             -> IO (Maybe (TyThing, Fixity, [Instance]))
1200
1201 -- Used to implemnent :info in GHCi
1202 --
1203 -- Look up a RdrName and return all the TyThings it might be
1204 -- A capitalised RdrName is given to us in the DataName namespace,
1205 -- but we want to treat it as *both* a data constructor 
1206 --  *and* as a type or class constructor; 
1207 -- hence the call to dataTcOccs, and we return up to two results
1208 tcRnGetInfo hsc_env name
1209   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1210     let ictxt = hsc_IC hsc_env in
1211     setInteractiveContext hsc_env ictxt $ do
1212
1213         -- Load the interface for all unqualified types and classes
1214         -- That way we will find all the instance declarations
1215         -- (Packages have not orphan modules, and we assume that
1216         --  in the home package all relevant modules are loaded.)
1217     loadUnqualIfaces ictxt
1218
1219     thing  <- tcLookupGlobal name
1220     fixity <- lookupFixityRn name
1221     ispecs <- lookupInsts (icPrintUnqual ictxt) thing
1222     return (thing, fixity, ispecs)
1223
1224
1225 lookupInsts :: PrintUnqualified -> TyThing -> TcM [Instance]
1226 -- Filter the instances by the ones whose tycons (or clases resp) 
1227 -- are in scope unqualified.  Otherwise we list a whole lot too many!
1228 lookupInsts print_unqual (AClass cls)
1229   = do  { inst_envs <- tcGetInstEnvs
1230         ; return [ ispec
1231                  | ispec <- classInstances inst_envs cls
1232                  , plausibleDFun print_unqual (instanceDFunId ispec) ] }
1233
1234 lookupInsts print_unqual (ATyCon tc)
1235   = do  { eps <- getEps -- Load all instances for all classes that are
1236                         -- in the type environment (which are all the ones
1237                         -- we've seen in any interface file so far)
1238         ; (pkg_ie, home_ie) <- tcGetInstEnvs    -- Search all
1239         ; return [ ispec
1240                  | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
1241                  , let dfun = instanceDFunId ispec
1242                  , relevant dfun
1243                  , plausibleDFun print_unqual dfun ] }
1244   where
1245     relevant df = tc_name `elemNameSet` tyClsNamesOfDFunHead (idType df)
1246     tc_name     = tyConName tc            
1247
1248 lookupInsts print_unqual other = return []
1249
1250 plausibleDFun print_unqual dfun -- Dfun involving only names that print unqualified
1251   = all ok (nameSetToList (tyClsNamesOfType (idType dfun)))
1252   where
1253     ok name | isBuiltInSyntax name = True
1254             | isExternalName name  = 
1255                 isNothing $ fst print_unqual (nameModule name) 
1256                                              (nameOccName name)
1257             | otherwise            = True
1258
1259 loadUnqualIfaces :: InteractiveContext -> TcM ()
1260 -- Load the home module for everything that is in scope unqualified
1261 -- This is so that we can accurately report the instances for 
1262 -- something
1263 loadUnqualIfaces ictxt
1264   = initIfaceTcRn $
1265     mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
1266   where
1267     unqual_mods = [ nameModule name
1268                   | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt),
1269                     let name = gre_name gre,
1270                     not (isInternalName name),
1271                     isTcOcc (nameOccName name),  -- Types and classes only
1272                     unQualOK gre ]               -- In scope unqualified
1273     doc = ptext SLIT("Need interface for module whose export(s) are in scope unqualified")
1274 #endif /* GHCI */
1275 \end{code}
1276
1277 %************************************************************************
1278 %*                                                                      *
1279                 Degugging output
1280 %*                                                                      *
1281 %************************************************************************
1282
1283 \begin{code}
1284 rnDump :: SDoc -> TcRn ()
1285 -- Dump, with a banner, if -ddump-rn
1286 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
1287
1288 tcDump :: TcGblEnv -> TcRn ()
1289 tcDump env
1290  = do { dflags <- getDOpts ;
1291
1292         -- Dump short output if -ddump-types or -ddump-tc
1293         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1294             (dumpTcRn short_dump) ;
1295
1296         -- Dump bindings if -ddump-tc
1297         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1298    }
1299   where
1300     short_dump = pprTcGblEnv env
1301     full_dump  = pprLHsBinds (tcg_binds env)
1302         -- NB: foreign x-d's have undefined's in their types; 
1303         --     hence can't show the tc_fords
1304
1305 tcCoreDump mod_guts
1306  = do { dflags <- getDOpts ;
1307         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1308             (dumpTcRn (pprModGuts mod_guts)) ;
1309
1310         -- Dump bindings if -ddump-tc
1311         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1312   where
1313     full_dump = pprCoreBindings (mg_binds mod_guts)
1314
1315 -- It's unpleasant having both pprModGuts and pprModDetails here
1316 pprTcGblEnv :: TcGblEnv -> SDoc
1317 pprTcGblEnv (TcGblEnv { tcg_type_env  = type_env, 
1318                         tcg_insts     = insts, 
1319                         tcg_fam_insts = fam_insts, 
1320                         tcg_rules     = rules,
1321                         tcg_imports   = imports })
1322   = vcat [ ppr_types insts type_env
1323          , ppr_insts insts
1324          , ppr_fam_insts fam_insts
1325          , vcat (map ppr rules)
1326          , ppr_gen_tycons (typeEnvTyCons type_env)
1327          , ptext SLIT("Dependent modules:") <+> ppr (eltsUFM (imp_dep_mods imports))
1328          , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1329
1330 pprModGuts :: ModGuts -> SDoc
1331 pprModGuts (ModGuts { mg_types = type_env,
1332                       mg_rules = rules })
1333   = vcat [ ppr_types [] type_env,
1334            ppr_rules rules ]
1335
1336 ppr_types :: [Instance] -> TypeEnv -> SDoc
1337 ppr_types insts type_env
1338   = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1339   where
1340     dfun_ids = map instanceDFunId insts
1341     ids = [id | id <- typeEnvIds type_env, want_sig id]
1342     want_sig id | opt_PprStyle_Debug = True
1343                 | otherwise          = isLocalId id && 
1344                                        isExternalName (idName id) && 
1345                                        not (id `elem` dfun_ids)
1346         -- isLocalId ignores data constructors, records selectors etc.
1347         -- The isExternalName ignores local dictionary and method bindings
1348         -- that the type checker has invented.  Top-level user-defined things 
1349         -- have External names.
1350
1351 ppr_insts :: [Instance] -> SDoc
1352 ppr_insts []     = empty
1353 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
1354
1355 ppr_fam_insts :: [FamInst] -> SDoc
1356 ppr_fam_insts []        = empty
1357 ppr_fam_insts fam_insts = 
1358   text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
1359
1360 ppr_sigs :: [Var] -> SDoc
1361 ppr_sigs ids
1362         -- Print type signatures; sort by OccName 
1363   = vcat (map ppr_sig (sortLe le_sig ids))
1364   where
1365     le_sig id1 id2 = getOccName id1 <= getOccName id2
1366     ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1367
1368 ppr_rules :: [CoreRule] -> SDoc
1369 ppr_rules [] = empty
1370 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1371                       nest 4 (pprRules rs),
1372                       ptext SLIT("#-}")]
1373
1374 ppr_gen_tycons []  = empty
1375 ppr_gen_tycons tcs = vcat [ptext SLIT("Tycons with generics:"),
1376                            nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]
1377 \end{code}