Rough matches for family instances
[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                 -- Remove any shadowed bindings from the type_env;
891                 -- they are inaccessible but might, I suppose, cause 
892                 -- a space leak if we leave them there
893         shadowed = [ n | name <- bound_names,
894                          let rdr_name = mkRdrUnqual (nameOccName name),
895                          Just n <- [lookupLocalRdrEnv rn_env rdr_name] ] ;
896
897         filtered_type_env = delListFromNameEnv type_env shadowed ;
898         new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;
899
900         new_ic = ictxt { ic_rn_local_env = new_rn_env, 
901                          ic_type_env     = new_type_env }
902     } ;
903
904     dumpOptTcRn Opt_D_dump_tc 
905         (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
906                text "Typechecked expr" <+> ppr zonked_expr]) ;
907
908     returnM (new_ic, bound_names, zonked_expr)
909     }
910   where
911     bad_unboxed id = addErr (sep [ptext SLIT("GHCi can't bind a variable of unlifted type:"),
912                                   nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
913
914 globaliseAndTidy :: Id -> Id
915 globaliseAndTidy id
916 -- Give the Id a Global Name, and tidy its type
917   = setIdType (globaliseId VanillaGlobal id) tidy_type
918   where
919     tidy_type = tidyTopType (idType id)
920 \end{code}
921
922 Here is the grand plan, implemented in tcUserStmt
923
924         What you type                   The IO [HValue] that hscStmt returns
925         -------------                   ------------------------------------
926         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
927                                         bindings: [x,y,...]
928
929         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
930                                         bindings: [x,y,...]
931
932         expr (of IO type)       ==>     expr >>= \ it -> return [coerce HVal it]
933           [NB: result not printed]      bindings: [it]
934           
935         expr (of non-IO type,   ==>     let it = expr in print it >> return [coerce HVal it]
936           result showable)              bindings: [it]
937
938         expr (of non-IO type, 
939           result not showable)  ==>     error
940
941
942 \begin{code}
943 ---------------------------
944 type PlanResult = ([Id], LHsExpr Id)
945 type Plan = TcM PlanResult
946
947 runPlans :: [Plan] -> TcM PlanResult
948 -- Try the plans in order.  If one fails (by raising an exn), try the next.
949 -- If one succeeds, take it.
950 runPlans []     = panic "runPlans"
951 runPlans [p]    = p
952 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
953
954 --------------------
955 mkPlan :: LStmt Name -> TcM PlanResult
956 mkPlan (L loc (ExprStmt expr _ _))      -- An expression typed at the prompt 
957   = do  { uniq <- newUnique             -- is treated very specially
958         ; let fresh_it  = itName uniq
959               the_bind  = L loc $ mkFunBind (L loc fresh_it) matches
960               matches   = [mkMatch [] expr emptyLocalBinds]
961               let_stmt  = L loc $ LetStmt (HsValBinds (ValBindsOut [(NonRecursive,unitBag the_bind)] []))
962               bind_stmt = L loc $ BindStmt (nlVarPat fresh_it) expr
963                                            (HsVar bindIOName) noSyntaxExpr 
964               print_it  = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar fresh_it))
965                                            (HsVar thenIOName) placeHolderType
966
967         -- The plans are:
968         --      [it <- e; print it]     but not if it::()
969         --      [it <- e]               
970         --      [let it = e; print it]  
971         ; runPlans [    -- Plan A
972                     do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
973                        ; it_ty <- zonkTcType (idType it_id)
974                        ; ifM (isUnitTy it_ty) failM
975                        ; return stuff },
976
977                         -- Plan B; a naked bind statment
978                     tcGhciStmts [bind_stmt],    
979
980                         -- Plan C; check that the let-binding is typeable all by itself.
981                         -- If not, fail; if so, try to print it.
982                         -- The two-step process avoids getting two errors: one from
983                         -- the expression itself, and one from the 'print it' part
984                         -- This two-step story is very clunky, alas
985                     do { checkNoErrs (tcGhciStmts [let_stmt]) 
986                                 --- checkNoErrs defeats the error recovery of let-bindings
987                        ; tcGhciStmts [let_stmt, print_it] }
988           ]}
989
990 mkPlan stmt@(L loc (BindStmt {}))
991   | [L _ v] <- collectLStmtBinders stmt         -- One binder, for a bind stmt 
992   = do  { let print_v  = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
993                                            (HsVar thenIOName) placeHolderType
994
995         ; print_bind_result <- doptM Opt_PrintBindResult
996         ; let print_plan = do
997                   { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
998                   ; v_ty <- zonkTcType (idType v_id)
999                   ; ifM (isUnitTy v_ty || not (isTauTy v_ty)) failM
1000                   ; return stuff }
1001
1002         -- The plans are:
1003         --      [stmt; print v]         but not if v::()
1004         --      [stmt]
1005         ; runPlans ((if print_bind_result then [print_plan] else []) ++
1006                     [tcGhciStmts [stmt]])
1007         }
1008
1009 mkPlan stmt
1010   = tcGhciStmts [stmt]
1011
1012 ---------------------------
1013 tcGhciStmts :: [LStmt Name] -> TcM PlanResult
1014 tcGhciStmts stmts
1015  = do { ioTyCon <- tcLookupTyCon ioTyConName ;
1016         ret_id  <- tcLookupId returnIOName ;            -- return @ IO
1017         let {
1018             io_ty     = mkTyConApp ioTyCon [] ;
1019             ret_ty    = mkListTy unitTy ;
1020             io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
1021             tc_io_stmts stmts = tcStmts DoExpr (tcDoStmt io_ty) stmts 
1022                                         (emptyRefinement, io_ret_ty) ;
1023
1024             names = map unLoc (collectLStmtsBinders stmts) ;
1025
1026                 -- mk_return builds the expression
1027                 --      returnIO @ [()] [coerce () x, ..,  coerce () z]
1028                 --
1029                 -- Despite the inconvenience of building the type applications etc,
1030                 -- this *has* to be done in type-annotated post-typecheck form
1031                 -- because we are going to return a list of *polymorphic* values
1032                 -- coerced to type (). If we built a *source* stmt
1033                 --      return [coerce x, ..., coerce z]
1034                 -- then the type checker would instantiate x..z, and we wouldn't
1035                 -- get their *polymorphic* values.  (And we'd get ambiguity errs
1036                 -- if they were overloaded, since they aren't applied to anything.)
1037             mk_return ids = nlHsApp (nlHsTyApp ret_id [ret_ty]) 
1038                                     (noLoc $ ExplicitList unitTy (map mk_item ids)) ;
1039             mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
1040                                  (nlHsVar id) 
1041          } ;
1042
1043         -- OK, we're ready to typecheck the stmts
1044         traceTc (text "tcs 2") ;
1045         ((tc_stmts, ids), lie) <- getLIE $ tc_io_stmts stmts $ \ _ ->
1046                                            mappM tcLookupId names ;
1047                                         -- Look up the names right in the middle,
1048                                         -- where they will all be in scope
1049
1050         -- Simplify the context
1051         const_binds <- checkNoErrs (tcSimplifyInteractive lie) ;
1052                 -- checkNoErrs ensures that the plan fails if context redn fails
1053
1054         return (ids, mkHsDictLet const_binds $
1055                      noLoc (HsDo DoExpr tc_stmts (mk_return ids) io_ret_ty))
1056     }
1057 \end{code}
1058
1059
1060 tcRnExpr just finds the type of an expression
1061
1062 \begin{code}
1063 tcRnExpr :: HscEnv
1064          -> InteractiveContext
1065          -> LHsExpr RdrName
1066          -> IO (Maybe Type)
1067 tcRnExpr hsc_env ictxt rdr_expr
1068   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1069     setInteractiveContext hsc_env ictxt $ do {
1070
1071     (rn_expr, fvs) <- rnLExpr rdr_expr ;
1072     failIfErrsM ;
1073
1074         -- Now typecheck the expression; 
1075         -- it might have a rank-2 type (e.g. :t runST)
1076     ((tc_expr, res_ty), lie)       <- getLIE (tcInferRho rn_expr) ;
1077     ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie)  ;
1078     tcSimplifyInteractive lie_top ;
1079     qtvs' <- mappM zonkQuantifiedTyVar qtvs ;
1080
1081     let { all_expr_ty = mkForAllTys qtvs' $
1082                         mkFunTys (map idType dict_ids)  $
1083                         res_ty } ;
1084     zonkTcType all_expr_ty
1085     }
1086   where
1087     smpl_doc = ptext SLIT("main expression")
1088 \end{code}
1089
1090 tcRnType just finds the kind of a type
1091
1092 \begin{code}
1093 tcRnType :: HscEnv
1094          -> InteractiveContext
1095          -> LHsType RdrName
1096          -> IO (Maybe Kind)
1097 tcRnType hsc_env ictxt rdr_type
1098   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1099     setInteractiveContext hsc_env ictxt $ do {
1100
1101     rn_type <- rnLHsType doc rdr_type ;
1102     failIfErrsM ;
1103
1104         -- Now kind-check the type
1105     (ty', kind) <- kcHsType rn_type ;
1106     return kind
1107     }
1108   where
1109     doc = ptext SLIT("In GHCi input")
1110
1111 #endif /* GHCi */
1112 \end{code}
1113
1114
1115 %************************************************************************
1116 %*                                                                      *
1117         More GHCi stuff, to do with browsing and getting info
1118 %*                                                                      *
1119 %************************************************************************
1120
1121 \begin{code}
1122 #ifdef GHCI
1123 -- ASSUMES that the module is either in the HomePackageTable or is
1124 -- a package module with an interface on disk.  If neither of these is
1125 -- true, then the result will be an error indicating the interface
1126 -- could not be found.
1127 getModuleExports :: HscEnv -> Module -> IO (Messages, Maybe NameSet)
1128 getModuleExports hsc_env mod
1129   = initTc hsc_env HsSrcFile iNTERACTIVE (tcGetModuleExports mod)
1130
1131 tcGetModuleExports :: Module -> TcM NameSet
1132 tcGetModuleExports mod = do
1133   let doc = ptext SLIT("context for compiling statements")
1134   iface <- initIfaceTcRn $ loadSysInterface doc mod
1135   loadOrphanModules (dep_orphs (mi_deps iface))
1136                 -- Load any orphan-module interfaces,
1137                 -- so their instances are visible
1138   ifaceExportNames (mi_exports iface)
1139
1140 tcRnLookupRdrName :: HscEnv -> RdrName -> IO (Maybe [Name])
1141 tcRnLookupRdrName hsc_env rdr_name 
1142   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1143     setInteractiveContext hsc_env (hsc_IC hsc_env) $ 
1144     lookup_rdr_name rdr_name
1145
1146 lookup_rdr_name rdr_name = do {
1147         -- If the identifier is a constructor (begins with an
1148         -- upper-case letter), then we need to consider both
1149         -- constructor and type class identifiers.
1150     let { rdr_names = dataTcOccs rdr_name } ;
1151
1152         -- results :: [Either Messages Name]
1153     results <- mapM (tryTcErrs . lookupOccRn) rdr_names ;
1154
1155     traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)]);
1156         -- The successful lookups will be (Just name)
1157     let { (warns_s, good_names) = unzip [ (msgs, name) 
1158                                         | (msgs, Just name) <- results] ;
1159           errs_s = [msgs | (msgs, Nothing) <- results] } ;
1160
1161         -- Fail if nothing good happened, else add warnings
1162     if null good_names then
1163                 -- No lookup succeeded, so
1164                 -- pick the first error message and report it
1165                 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
1166                 --       while the other is "X is not in scope", 
1167                 --       we definitely want the former; but we might pick the latter
1168         do { addMessages (head errs_s) ; failM }
1169       else                      -- Add deprecation warnings
1170         mapM_ addMessages warns_s ;
1171     
1172     return good_names
1173  }
1174
1175
1176 tcRnLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
1177 tcRnLookupName hsc_env name
1178   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1179     setInteractiveContext hsc_env (hsc_IC hsc_env) $
1180     tcLookupGlobal name
1181
1182
1183 tcRnGetInfo :: HscEnv
1184             -> Name
1185             -> IO (Maybe (TyThing, Fixity, [Instance]))
1186
1187 -- Used to implemnent :info in GHCi
1188 --
1189 -- Look up a RdrName and return all the TyThings it might be
1190 -- A capitalised RdrName is given to us in the DataName namespace,
1191 -- but we want to treat it as *both* a data constructor 
1192 --  *and* as a type or class constructor; 
1193 -- hence the call to dataTcOccs, and we return up to two results
1194 tcRnGetInfo hsc_env name
1195   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1196     let ictxt = hsc_IC hsc_env in
1197     setInteractiveContext hsc_env ictxt $ do
1198
1199         -- Load the interface for all unqualified types and classes
1200         -- That way we will find all the instance declarations
1201         -- (Packages have not orphan modules, and we assume that
1202         --  in the home package all relevant modules are loaded.)
1203     loadUnqualIfaces ictxt
1204
1205     thing  <- tcLookupGlobal name
1206     fixity <- lookupFixityRn name
1207     ispecs <- lookupInsts (icPrintUnqual ictxt) thing
1208     return (thing, fixity, ispecs)
1209
1210
1211 lookupInsts :: PrintUnqualified -> TyThing -> TcM [Instance]
1212 -- Filter the instances by the ones whose tycons (or clases resp) 
1213 -- are in scope unqualified.  Otherwise we list a whole lot too many!
1214 lookupInsts print_unqual (AClass cls)
1215   = do  { inst_envs <- tcGetInstEnvs
1216         ; return [ ispec
1217                  | ispec <- classInstances inst_envs cls
1218                  , plausibleDFun print_unqual (instanceDFunId ispec) ] }
1219
1220 lookupInsts print_unqual (ATyCon tc)
1221   = do  { eps <- getEps -- Load all instances for all classes that are
1222                         -- in the type environment (which are all the ones
1223                         -- we've seen in any interface file so far)
1224         ; (pkg_ie, home_ie) <- tcGetInstEnvs    -- Search all
1225         ; return [ ispec
1226                  | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
1227                  , let dfun = instanceDFunId ispec
1228                  , relevant dfun
1229                  , plausibleDFun print_unqual dfun ] }
1230   where
1231     relevant df = tc_name `elemNameSet` tyClsNamesOfDFunHead (idType df)
1232     tc_name     = tyConName tc            
1233
1234 lookupInsts print_unqual other = return []
1235
1236 plausibleDFun print_unqual dfun -- Dfun involving only names that print unqualified
1237   = all ok (nameSetToList (tyClsNamesOfType (idType dfun)))
1238   where
1239     ok name | isBuiltInSyntax name = True
1240             | isExternalName name  = 
1241                 isNothing $ fst print_unqual (nameModule name) 
1242                                              (nameOccName name)
1243             | otherwise            = True
1244
1245 loadUnqualIfaces :: InteractiveContext -> TcM ()
1246 -- Load the home module for everything that is in scope unqualified
1247 -- This is so that we can accurately report the instances for 
1248 -- something
1249 loadUnqualIfaces ictxt
1250   = initIfaceTcRn $
1251     mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
1252   where
1253     unqual_mods = [ nameModule name
1254                   | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt),
1255                     let name = gre_name gre,
1256                     not (isInternalName name),
1257                     isTcOcc (nameOccName name),  -- Types and classes only
1258                     unQualOK gre ]               -- In scope unqualified
1259     doc = ptext SLIT("Need interface for module whose export(s) are in scope unqualified")
1260 #endif /* GHCI */
1261 \end{code}
1262
1263 %************************************************************************
1264 %*                                                                      *
1265                 Degugging output
1266 %*                                                                      *
1267 %************************************************************************
1268
1269 \begin{code}
1270 rnDump :: SDoc -> TcRn ()
1271 -- Dump, with a banner, if -ddump-rn
1272 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
1273
1274 tcDump :: TcGblEnv -> TcRn ()
1275 tcDump env
1276  = do { dflags <- getDOpts ;
1277
1278         -- Dump short output if -ddump-types or -ddump-tc
1279         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1280             (dumpTcRn short_dump) ;
1281
1282         -- Dump bindings if -ddump-tc
1283         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1284    }
1285   where
1286     short_dump = pprTcGblEnv env
1287     full_dump  = pprLHsBinds (tcg_binds env)
1288         -- NB: foreign x-d's have undefined's in their types; 
1289         --     hence can't show the tc_fords
1290
1291 tcCoreDump mod_guts
1292  = do { dflags <- getDOpts ;
1293         ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1294             (dumpTcRn (pprModGuts mod_guts)) ;
1295
1296         -- Dump bindings if -ddump-tc
1297         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1298   where
1299     full_dump = pprCoreBindings (mg_binds mod_guts)
1300
1301 -- It's unpleasant having both pprModGuts and pprModDetails here
1302 pprTcGblEnv :: TcGblEnv -> SDoc
1303 pprTcGblEnv (TcGblEnv { tcg_type_env  = type_env, 
1304                         tcg_insts     = insts, 
1305                         tcg_fam_insts = fam_insts, 
1306                         tcg_rules     = rules,
1307                         tcg_imports   = imports })
1308   = vcat [ ppr_types insts type_env
1309          , ppr_insts insts
1310          , ppr_fam_insts fam_insts
1311          , vcat (map ppr rules)
1312          , ppr_gen_tycons (typeEnvTyCons type_env)
1313          , ptext SLIT("Dependent modules:") <+> ppr (eltsUFM (imp_dep_mods imports))
1314          , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1315
1316 pprModGuts :: ModGuts -> SDoc
1317 pprModGuts (ModGuts { mg_types = type_env,
1318                       mg_rules = rules })
1319   = vcat [ ppr_types [] type_env,
1320            ppr_rules rules ]
1321
1322 ppr_types :: [Instance] -> TypeEnv -> SDoc
1323 ppr_types insts type_env
1324   = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1325   where
1326     dfun_ids = map instanceDFunId insts
1327     ids = [id | id <- typeEnvIds type_env, want_sig id]
1328     want_sig id | opt_PprStyle_Debug = True
1329                 | otherwise          = isLocalId id && 
1330                                        isExternalName (idName id) && 
1331                                        not (id `elem` dfun_ids)
1332         -- isLocalId ignores data constructors, records selectors etc.
1333         -- The isExternalName ignores local dictionary and method bindings
1334         -- that the type checker has invented.  Top-level user-defined things 
1335         -- have External names.
1336
1337 ppr_insts :: [Instance] -> SDoc
1338 ppr_insts []     = empty
1339 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
1340
1341 ppr_fam_insts :: [FamInst] -> SDoc
1342 ppr_fam_insts []        = empty
1343 ppr_fam_insts fam_insts = 
1344   text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
1345
1346 ppr_sigs :: [Var] -> SDoc
1347 ppr_sigs ids
1348         -- Print type signatures; sort by OccName 
1349   = vcat (map ppr_sig (sortLe le_sig ids))
1350   where
1351     le_sig id1 id2 = getOccName id1 <= getOccName id2
1352     ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1353
1354 ppr_rules :: [CoreRule] -> SDoc
1355 ppr_rules [] = empty
1356 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1357                       nest 4 (pprRules rs),
1358                       ptext SLIT("#-}")]
1359
1360 ppr_gen_tycons []  = empty
1361 ppr_gen_tycons tcs = vcat [ptext SLIT("Tycons with generics:"),
1362                            nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]
1363 \end{code}