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