Make typechecker top-level functions also return messages instead of
[ghc-hetmet.git] / compiler / typecheck / TcRnDriver.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[TcModule]{Typechecking a whole module}
6
7 \begin{code}
8 {-# OPTIONS -w #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 module TcRnDriver (
16 #ifdef GHCI
17         tcRnStmt, tcRnExpr, tcRnType,
18         tcRnLookupRdrName,
19         tcRnLookupName,
20         tcRnGetInfo,
21         getModuleExports, 
22 #endif
23         tcRnModule, 
24         tcTopSrcDecls,
25         tcRnExtCore
26     ) where
27
28 import IO
29 #ifdef GHCI
30 import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
31 #endif
32
33 import DynFlags
34 import StaticFlags
35 import HsSyn
36 import RdrHsSyn
37
38 import PrelNames
39 import RdrName
40 import TcHsSyn
41 import TcExpr
42 import TcRnMonad
43 import TcType
44 import Inst
45 import FamInst
46 import InstEnv
47 import FamInstEnv
48 import TcBinds
49 import TcDefaults
50 import TcEnv
51 import TcRules
52 import TcForeign
53 import TcInstDcls
54 import TcIface
55 import MkIface
56 import IfaceSyn
57 import TcSimplify
58 import TcTyClsDecls
59 import TcUnify  ( withBox )
60 import LoadIface
61 import RnNames
62 import RnEnv
63 import RnSource
64 import RnHsDoc
65 import PprCore
66 import CoreSyn
67 import ErrUtils
68 import Id
69 import VarEnv
70 import Var
71 import Module
72 import LazyUniqFM
73 import Name
74 import NameEnv
75 import NameSet
76 import TyCon
77 import TysWiredIn
78 import SrcLoc
79 import HscTypes
80 import ListSetOps
81 import Outputable
82 import DataCon
83 import Type
84 import Class
85 import Data.List ( sortBy )
86
87 #ifdef GHCI
88 import Linker
89 import TcHsType
90 import TcMType
91 import TcMatches
92 import RnTypes
93 import RnExpr
94 import IfaceEnv
95 import MkId
96 import IdInfo
97 import {- Kind parts of -} Type
98 import BasicTypes
99 import Foreign.Ptr( Ptr )
100 #endif
101
102 import FastString
103 import Maybes
104 import Util
105 import Bag
106
107 import Control.Monad
108 import Data.Maybe       ( isJust )
109
110 #include "HsVersions.h"
111 \end{code}
112
113
114
115 %************************************************************************
116 %*                                                                      *
117         Typecheck and rename a module
118 %*                                                                      *
119 %************************************************************************
120
121
122 \begin{code}
123 tcRnModule :: HscEnv 
124            -> HscSource
125            -> Bool              -- True <=> save renamed syntax
126            -> Located (HsModule RdrName)
127            -> IO (Messages, Maybe TcGblEnv)
128
129 tcRnModule hsc_env hsc_src save_rn_syntax
130          (L loc (HsModule maybe_mod export_ies 
131                           import_decls local_decls mod_deprec
132                           module_info maybe_doc))
133  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
134
135    let { this_pkg = thisPackage (hsc_dflags hsc_env) ;
136          this_mod = case maybe_mod of
137                         Nothing  -> mAIN        -- 'module M where' is omitted
138                         Just (L _ mod) -> mkModule this_pkg mod } ;
139                                                 -- The normal case
140                 
141    initTc hsc_env hsc_src save_rn_syntax this_mod $ 
142    setSrcSpan loc $
143    do {         -- Deal with imports;
144         tcg_env <- tcRnImports hsc_env this_mod import_decls ;
145         setGblEnv tcg_env               $ do {
146
147                 -- Load the hi-boot interface for this module, if any
148                 -- We do this now so that the boot_names can be passed
149                 -- to tcTyAndClassDecls, because the boot_names are 
150                 -- automatically considered to be loop breakers
151                 --
152                 -- Do this *after* tcRnImports, so that we know whether
153                 -- a module that we import imports us; and hence whether to
154                 -- look for a hi-boot file
155         boot_iface <- tcHiBootIface hsc_src this_mod ;
156
157                 -- Rename and type check the declarations
158         traceRn (text "rn1a") ;
159         tcg_env <- if isHsBoot hsc_src then
160                         tcRnHsBootDecls local_decls
161                    else 
162                         tcRnSrcDecls boot_iface local_decls ;
163         setGblEnv tcg_env               $ do {
164
165                 -- Report the use of any deprecated things
166                 -- We do this *before* processsing the export list so
167                 -- that we don't bleat about re-exporting a deprecated
168                 -- thing (especially via 'module Foo' export item)
169                 -- That is, only uses in the *body* of the module are complained about
170         traceRn (text "rn3") ;
171         failIfErrsM ;   -- finishWarnings crashes sometimes 
172                         -- as a result of typechecker repairs (e.g. unboundNames)
173         tcg_env <- finishWarnings (hsc_dflags hsc_env) mod_deprec tcg_env ;
174
175                 -- Process the export list
176         traceRn (text "rn4a: before exports");
177         tcg_env <- rnExports (isJust maybe_mod) export_ies tcg_env ;
178         traceRn (text "rn4b: after exportss") ;
179
180         -- Compare the hi-boot iface (if any) with the real thing
181         -- Must be done after processing the exports
182         tcg_env <- checkHiBootIface tcg_env boot_iface ;
183
184         -- The new type env is already available to stuff slurped from 
185         -- interface files, via TcEnv.updateGlobalTypeEnv
186         -- It's important that this includes the stuff in checkHiBootIface, 
187         -- because the latter might add new bindings for boot_dfuns, 
188         -- which may be mentioned in imported unfoldings
189
190                 -- Rename the Haddock documentation 
191         tcg_env <- rnHaddock module_info maybe_doc tcg_env ;
192
193                 -- Report unused names
194         reportUnusedNames export_ies tcg_env ;
195
196                 -- Dump output and return
197         tcDump tcg_env ;
198         return tcg_env
199     }}}}
200 \end{code}
201
202
203 %************************************************************************
204 %*                                                                      *
205                 Import declarations
206 %*                                                                      *
207 %************************************************************************
208
209 \begin{code}
210 tcRnImports :: HscEnv -> Module -> [LImportDecl RdrName] -> TcM TcGblEnv
211 tcRnImports hsc_env this_mod import_decls
212   = do  { (rn_imports, rdr_env, imports,hpc_info) <- rnImports import_decls ;
213
214         ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
215               ; dep_mods = imp_dep_mods imports
216
217                 -- We want instance declarations from all home-package
218                 -- modules below this one, including boot modules, except
219                 -- ourselves.  The 'except ourselves' is so that we don't
220                 -- get the instances from this module's hs-boot file
221               ; want_instances :: ModuleName -> Bool
222               ; want_instances mod = mod `elemUFM` dep_mods
223                                    && mod /= moduleName this_mod
224               ; (home_insts, home_fam_insts) = hptInstances hsc_env 
225                                                             want_instances
226               } ;
227
228                 -- Record boot-file info in the EPS, so that it's 
229                 -- visible to loadHiBootInterface in tcRnSrcDecls,
230                 -- and any other incrementally-performed imports
231         ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
232
233                 -- Update the gbl env
234         ; updGblEnv ( \ gbl -> 
235             gbl { 
236               tcg_rdr_env      = plusOccEnv (tcg_rdr_env gbl) rdr_env,
237               tcg_imports      = tcg_imports gbl `plusImportAvails` imports,
238               tcg_rn_imports   = fmap (const rn_imports) (tcg_rn_imports gbl),
239               tcg_inst_env     = extendInstEnvList (tcg_inst_env gbl) home_insts,
240               tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl) 
241                                                       home_fam_insts,
242               tcg_hpc          = hpc_info
243             }) $ do {
244
245         ; traceRn (text "rn1" <+> ppr (imp_dep_mods imports))
246                 -- Fail if there are any errors so far
247                 -- The error printing (if needed) takes advantage 
248                 -- of the tcg_env we have now set
249 --      ; traceIf (text "rdr_env: " <+> ppr rdr_env)
250         ; failIfErrsM
251
252                 -- Load any orphan-module and family instance-module
253                 -- interfaces, so that their rules and instance decls will be
254                 -- found.
255         ; loadOrphanModules (imp_orphs  imports) False
256         ; loadOrphanModules (imp_finsts imports) True 
257
258                 -- Check type-familily consistency
259         ; traceRn (text "rn1: checking family instance consistency")
260         ; let { dir_imp_mods = moduleEnvKeys
261                              . imp_mods 
262                              $ imports }
263         ; checkFamInstConsistency (imp_finsts imports) dir_imp_mods ;
264
265         ; getGblEnv } }
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271         Type-checking external-core modules
272 %*                                                                      *
273 %************************************************************************
274
275 \begin{code}
276 tcRnExtCore :: HscEnv 
277             -> HsExtCore RdrName
278             -> IO (Messages, Maybe ModGuts)
279         -- Nothing => some error occurred 
280
281 tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
282         -- The decls are IfaceDecls; all names are original names
283  = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
284
285    initTc hsc_env ExtCoreFile False this_mod $ do {
286
287    let { ldecls  = map noLoc decls } ;
288
289        -- bring the type and class decls into scope
290        -- ToDo: check that this doesn't need to extract the val binds.
291        --       It seems that only the type and class decls need to be in scope below because
292        --          (a) tcTyAndClassDecls doesn't need the val binds, and 
293        --          (b) tcExtCoreBindings doesn't need anything
294        --              (in fact, it might not even need to be in the scope of
295        --               this tcg_env at all)
296    avails  <- getLocalNonValBinders (mkFakeGroup ldecls) ;
297    tc_envs <- extendGlobalRdrEnvRn False avails 
298                                    emptyFsEnv {- no fixity decls -} ;
299
300    setEnvs tc_envs $ do {
301
302    rn_decls <- checkNoErrs $ rnTyClDecls ldecls ;
303
304         -- Dump trace of renaming part
305    rnDump (ppr rn_decls) ;
306
307         -- Typecheck them all together so that
308         -- any mutually recursive types are done right
309    tcg_env <- tcTyAndClassDecls emptyModDetails rn_decls ;
310         -- Make the new type env available to stuff slurped from interface files
311
312    setGblEnv tcg_env $ do {
313    
314         -- Now the core bindings
315    core_binds <- initIfaceExtCore (tcExtCoreBindings src_binds) ;
316
317         -- Wrap up
318    let {
319         bndrs      = bindersOfBinds core_binds ;
320         my_exports = map (Avail . idName) bndrs ;
321                 -- ToDo: export the data types also?
322
323         final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
324
325         mod_guts = ModGuts {    mg_module    = this_mod,
326                                 mg_boot      = False,
327                                 mg_used_names = emptyNameSet, -- ToDo: compute usage
328                                 mg_dir_imps  = emptyModuleEnv, -- ??
329                                 mg_deps      = noDependencies,  -- ??
330                                 mg_exports   = my_exports,
331                                 mg_types     = final_type_env,
332                                 mg_insts     = tcg_insts tcg_env,
333                                 mg_fam_insts = tcg_fam_insts tcg_env,
334                                 mg_inst_env  = tcg_inst_env tcg_env,
335                                 mg_fam_inst_env = tcg_fam_inst_env tcg_env,
336                                 mg_rules     = [],
337                                 mg_binds     = core_binds,
338
339                                 -- Stubs
340                                 mg_rdr_env   = emptyGlobalRdrEnv,
341                                 mg_fix_env   = emptyFixityEnv,
342                                 mg_warns     = NoWarnings,
343                                 mg_foreign   = NoStubs,
344                                 mg_hpc_info  = emptyHpcInfo False,
345                                 mg_modBreaks = emptyModBreaks,
346                                 mg_vect_info = noVectInfo
347                     } } ;
348
349    tcCoreDump mod_guts ;
350
351    return mod_guts
352    }}}}
353
354 mkFakeGroup decls -- Rather clumsy; lots of unused fields
355   = emptyRdrGroup { hs_tyclds = decls }
356 \end{code}
357
358
359 %************************************************************************
360 %*                                                                      *
361         Type-checking the top level of a module
362 %*                                                                      *
363 %************************************************************************
364
365 \begin{code}
366 tcRnSrcDecls :: ModDetails -> [LHsDecl RdrName] -> TcM TcGblEnv
367         -- Returns the variables free in the decls
368         -- Reason: solely to report unused imports and bindings
369 tcRnSrcDecls boot_iface decls
370  = do {         -- Do all the declarations
371         (tc_envs, lie) <- getLIE $ tc_rn_src_decls boot_iface decls ;
372
373              --         Finish simplifying class constraints
374              -- 
375              -- tcSimplifyTop deals with constant or ambiguous InstIds.  
376              -- How could there be ambiguous ones?  They can only arise if a
377              -- top-level decl falls under the monomorphism restriction
378              -- and no subsequent decl instantiates its type.
379              --
380              -- We do this after checkMain, so that we use the type info 
381              -- thaat checkMain adds
382              -- 
383              -- We do it with both global and local env in scope:
384              --  * the global env exposes the instances to tcSimplifyTop
385              --  * the local env exposes the local Ids to tcSimplifyTop, 
386              --    so that we get better error messages (monomorphism restriction)
387         traceTc (text "Tc8") ;
388         inst_binds <- setEnvs tc_envs (tcSimplifyTop lie) ;
389
390             -- Backsubstitution.  This must be done last.
391             -- Even tcSimplifyTop may do some unification.
392         traceTc (text "Tc9") ;
393         let { (tcg_env, _) = tc_envs
394             ; TcGblEnv { tcg_type_env = type_env, tcg_binds = binds, 
395                          tcg_rules = rules, tcg_fords = fords } = tcg_env
396             ; all_binds = binds `unionBags` inst_binds } ;
397
398         failIfErrsM ;   -- Don't zonk if there have been errors
399                         -- It's a waste of time; and we may get debug warnings
400                         -- about strangely-typed TyCons!
401
402         (bind_ids, binds', fords', rules') <- zonkTopDecls all_binds rules fords ;
403
404         
405         let { final_type_env = extendTypeEnvWithIds type_env bind_ids
406             ; tcg_env' = tcg_env { tcg_binds = binds',
407                                    tcg_rules = rules', 
408                                    tcg_fords = fords' } } ;
409
410         setGlobalTypeEnv tcg_env' final_type_env                                   
411    }
412
413 tc_rn_src_decls :: ModDetails -> [LHsDecl RdrName] -> TcM (TcGblEnv, TcLclEnv)
414 -- Loops around dealing with each top level inter-splice group 
415 -- in turn, until it's dealt with the entire module
416 tc_rn_src_decls boot_details ds
417  = do { let { (first_group, group_tail) = findSplice ds } ;
418                 -- If ds is [] we get ([], Nothing)
419
420         -- Deal with decls up to, but not including, the first splice
421         (tcg_env, rn_decls) <- rnTopSrcDecls first_group ;
422                 -- rnTopSrcDecls fails if there are any errors
423
424         (tcg_env, tcl_env) <- setGblEnv tcg_env $ 
425                               tcTopSrcDecls boot_details rn_decls ;
426
427         -- If there is no splice, we're nearly done
428         setEnvs (tcg_env, tcl_env) $ 
429         case group_tail of {
430            Nothing -> do { tcg_env <- checkMain ;       -- Check for `main'
431                            return (tcg_env, tcl_env) 
432                       } ;
433
434         -- If there's a splice, we must carry on
435            Just (SpliceDecl splice_expr, rest_ds) -> do {
436 #ifndef GHCI
437         failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
438 #else
439
440         -- Rename the splice expression, and get its supporting decls
441         (rn_splice_expr, splice_fvs) <- checkNoErrs (rnLExpr splice_expr) ;
442                 -- checkNoErrs: don't typecheck if renaming failed
443         rnDump (ppr rn_splice_expr) ;
444
445         -- Execute the splice
446         spliced_decls <- tcSpliceDecls rn_splice_expr ;
447
448         -- Glue them on the front of the remaining decls and loop
449         setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
450         tc_rn_src_decls boot_details (spliced_decls ++ rest_ds)
451 #endif /* GHCI */
452     } } }
453 \end{code}
454
455 %************************************************************************
456 %*                                                                      *
457         Compiling hs-boot source files, and
458         comparing the hi-boot interface with the real thing
459 %*                                                                      *
460 %************************************************************************
461
462 \begin{code}
463 tcRnHsBootDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
464 tcRnHsBootDecls decls
465    = do { let { (first_group, group_tail) = findSplice decls }
466
467         ; case group_tail of
468              Just stuff -> spliceInHsBootErr stuff
469              Nothing    -> return ()
470
471                 -- Rename the declarations
472         ; (tcg_env, rn_group) <- rnTopSrcDecls first_group
473         ; setGblEnv tcg_env $ do {
474
475         -- Todo: check no foreign decls, no rules, no default decls
476
477                 -- Typecheck type/class decls
478         ; traceTc (text "Tc2")
479         ; let tycl_decls = hs_tyclds rn_group
480         ; tcg_env <- tcTyAndClassDecls emptyModDetails tycl_decls
481         ; setGblEnv tcg_env     $ do {
482
483                 -- Typecheck instance decls
484         ; traceTc (text "Tc3")
485         ; (tcg_env, inst_infos, _deriv_binds) 
486             <- tcInstDecls1 tycl_decls (hs_instds rn_group) (hs_derivds rn_group)
487         ; setGblEnv tcg_env     $ do {
488
489                 -- Typecheck value declarations
490         ; traceTc (text "Tc5") 
491         ; val_ids <- tcHsBootSigs (hs_valds rn_group)
492
493                 -- Wrap up
494                 -- No simplification or zonking to do
495         ; traceTc (text "Tc7a")
496         ; gbl_env <- getGblEnv 
497         
498                 -- Make the final type-env
499                 -- Include the dfun_ids so that their type sigs
500                 -- are written into the interface file
501         ; let { type_env0 = tcg_type_env gbl_env
502               ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
503               ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids 
504               ; dfun_ids = map iDFunId inst_infos }
505         ; setGlobalTypeEnv gbl_env type_env2  
506    }}}}
507
508 spliceInHsBootErr (SpliceDecl (L loc _), _)
509   = addErrAt loc (ptext (sLit "Splices are not allowed in hs-boot files"))
510 \end{code}
511
512 Once we've typechecked the body of the module, we want to compare what
513 we've found (gathered in a TypeEnv) with the hi-boot details (if any).
514
515 \begin{code}
516 checkHiBootIface :: TcGblEnv -> ModDetails -> TcM TcGblEnv
517 -- Compare the hi-boot file for this module (if there is one)
518 -- with the type environment we've just come up with
519 -- In the common case where there is no hi-boot file, the list
520 -- of boot_names is empty.
521 --
522 -- The bindings we return give bindings for the dfuns defined in the
523 -- hs-boot file, such as        $fbEqT = $fEqT
524
525 checkHiBootIface
526         tcg_env@(TcGblEnv { tcg_src = hs_src, tcg_binds = binds,
527                             tcg_insts = local_insts, tcg_fam_insts = local_fam_insts,
528                             tcg_type_env = local_type_env, tcg_exports = local_exports })
529         (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
530                       md_types = boot_type_env, md_exports = boot_exports })
531   | isHsBoot hs_src     -- Current module is already a hs-boot file!
532   = return tcg_env      
533
534   | otherwise
535   = do  { traceTc (text "checkHiBootIface" <+> (ppr boot_type_env $$ ppr boot_insts $$ 
536                                 ppr boot_exports)) ;
537
538                 -- Check the exports of the boot module, one by one
539         ; mapM_ check_export boot_exports
540
541                 -- Check for no family instances
542         ; unless (null boot_fam_insts) $
543             panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
544                    "instances in boot files yet...")
545             -- FIXME: Why?  The actual comparison is not hard, but what would
546             --        be the equivalent to the dfun bindings returned for class
547             --        instances?  We can't easily equate tycons...
548
549                 -- Check instance declarations
550         ; mb_dfun_prs <- mapM check_inst boot_insts
551         ; let tcg_env' = tcg_env { tcg_binds = binds `unionBags` dfun_binds }
552               final_type_env = extendTypeEnvWithIds local_type_env boot_dfuns
553               dfun_prs   = catMaybes mb_dfun_prs
554               boot_dfuns = map fst dfun_prs
555               dfun_binds = listToBag [ noLoc $ VarBind boot_dfun (nlHsVar dfun)
556                                      | (boot_dfun, dfun) <- dfun_prs ]
557
558         ; failIfErrsM
559         ; setGlobalTypeEnv tcg_env' final_type_env }
560   where
561     check_export boot_avail     -- boot_avail is exported by the boot iface
562       | name `elem` dfun_names = return ()      
563       | isWiredInName name     = return ()      -- No checking for wired-in names.  In particular,
564                                                 -- 'error' is handled by a rather gross hack
565                                                 -- (see comments in GHC.Err.hs-boot)
566
567         -- Check that the actual module exports the same thing
568       | not (null missing_names)
569       = addErrAt (nameSrcSpan (head missing_names)) 
570                  (missingBootThing (head missing_names) "exported by")
571
572         -- If the boot module does not *define* the thing, we are done
573         -- (it simply re-exports it, and names match, so nothing further to do)
574       | isNothing mb_boot_thing = return ()
575
576         -- Check that the actual module also defines the thing, and 
577         -- then compare the definitions
578       | Just real_thing <- lookupTypeEnv local_type_env name,
579         Just boot_thing <- mb_boot_thing
580       = when (not (checkBootDecl boot_thing real_thing))
581             $ addErrAt (nameSrcSpan (getName boot_thing))
582                        (let boot_decl = tyThingToIfaceDecl 
583                                                (fromJust mb_boot_thing)
584                             real_decl = tyThingToIfaceDecl real_thing
585                         in bootMisMatch real_thing boot_decl real_decl)
586
587       | otherwise
588       = addErrTc (missingBootThing name "defined in")
589       where
590         name          = availName boot_avail
591         mb_boot_thing = lookupTypeEnv boot_type_env name
592         missing_names = case lookupNameEnv local_export_env name of
593                           Nothing    -> [name]
594                           Just avail -> availNames boot_avail `minusList` availNames avail
595                  
596     dfun_names = map getName boot_insts
597
598     local_export_env :: NameEnv AvailInfo
599     local_export_env = availsToNameEnv local_exports
600
601     check_inst :: Instance -> TcM (Maybe (Id, Id))
602         -- Returns a pair of the boot dfun in terms of the equivalent real dfun
603     check_inst boot_inst
604         = case [dfun | inst <- local_insts, 
605                        let dfun = instanceDFunId inst,
606                        idType dfun `tcEqType` boot_inst_ty ] of
607             [] -> do { addErrTc (instMisMatch boot_inst); return Nothing }
608             (dfun:_) -> return (Just (local_boot_dfun, dfun))
609         where
610           boot_dfun = instanceDFunId boot_inst
611           boot_inst_ty = idType boot_dfun
612           local_boot_dfun = Id.mkExportedLocalId (idName boot_dfun) boot_inst_ty
613
614
615 -- This has to compare the TyThing from the .hi-boot file to the TyThing
616 -- in the current source file.  We must be careful to allow alpha-renaming
617 -- where appropriate, and also the boot declaration is allowed to omit
618 -- constructors and class methods.
619 --
620 -- See rnfail055 for a good test of this stuff.
621
622 checkBootDecl :: TyThing -> TyThing -> Bool
623
624 checkBootDecl (AnId id1) (AnId id2)
625   = ASSERT(id1 == id2) 
626     (idType id1 `tcEqType` idType id2)
627
628 checkBootDecl (ATyCon tc1) (ATyCon tc2)
629   | isSynTyCon tc1 && isSynTyCon tc2
630   = ASSERT(tc1 == tc2)
631     let tvs1 = tyConTyVars tc1; tvs2 = tyConTyVars tc2
632         env = rnBndrs2 env0 tvs1 tvs2
633
634         eqSynRhs (OpenSynTyCon k1 _) (OpenSynTyCon k2 _)
635             = tcEqTypeX env k1 k2
636         eqSynRhs (SynonymTyCon t1) (SynonymTyCon t2)
637             = tcEqTypeX env t1 t2
638     in
639     equalLength tvs1 tvs2 &&
640     eqSynRhs (synTyConRhs tc1) (synTyConRhs tc2)
641
642   | isAlgTyCon tc1 && isAlgTyCon tc2
643   = ASSERT(tc1 == tc2)
644     eqListBy tcEqPred (tyConStupidTheta tc1) (tyConStupidTheta tc2)
645     && eqAlgRhs (algTyConRhs tc1) (algTyConRhs tc2)
646
647   | isForeignTyCon tc1 && isForeignTyCon tc2
648   = tyConExtName tc1 == tyConExtName tc2
649   where 
650         env0 = mkRnEnv2 emptyInScopeSet
651
652         eqAlgRhs AbstractTyCon _ = True
653         eqAlgRhs OpenTyCon{} OpenTyCon{} = True
654         eqAlgRhs tc1@DataTyCon{} tc2@DataTyCon{} =
655             eqListBy eqCon (data_cons tc1) (data_cons tc2)
656         eqAlgRhs tc1@NewTyCon{} tc2@NewTyCon{} =
657             eqCon (data_con tc1) (data_con tc2)
658         eqAlgRhs _ _ = False
659
660         eqCon c1 c2
661           =  dataConName c1 == dataConName c2
662           && dataConIsInfix c1 == dataConIsInfix c2
663           && dataConStrictMarks c1 == dataConStrictMarks c2
664           && dataConFieldLabels c1 == dataConFieldLabels c2
665           && let tvs1 = dataConUnivTyVars c1 ++ dataConExTyVars c1
666                  tvs2 = dataConUnivTyVars c2 ++ dataConExTyVars c2
667                  env = rnBndrs2 env0 tvs1 tvs2
668              in
669               equalLength tvs1 tvs2 &&              
670               eqListBy (tcEqPredX env)
671                         (dataConEqTheta c1 ++ dataConDictTheta c1)
672                         (dataConEqTheta c2 ++ dataConDictTheta c2) &&
673               eqListBy (tcEqTypeX env)
674                         (dataConOrigArgTys c1)
675                         (dataConOrigArgTys c2)
676
677 checkBootDecl (AClass c1)  (AClass c2)
678   = let 
679        (clas_tyvars1, clas_fds1, sc_theta1, _, _, op_stuff1) 
680           = classExtraBigSig c1
681        (clas_tyvars2, clas_fds2, sc_theta2, _, _, op_stuff2) 
682           = classExtraBigSig c2
683
684        env0 = mkRnEnv2 emptyInScopeSet
685        env = rnBndrs2 env0 clas_tyvars1 clas_tyvars2
686
687        eqSig (id1, def_meth1) (id2, def_meth2)
688          = idName id1 == idName id2 &&
689            tcEqTypeX env op_ty1 op_ty2
690          where
691           (_, rho_ty1) = splitForAllTys (idType id1)
692           op_ty1 = funResultTy rho_ty1
693           (_, rho_ty2) = splitForAllTys (idType id2)
694           op_ty2 = funResultTy rho_ty2
695
696        eqFD (as1,bs1) (as2,bs2) = 
697          eqListBy (tcEqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
698          eqListBy (tcEqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
699     in
700        equalLength clas_tyvars1 clas_tyvars2 &&
701        eqListBy eqFD clas_fds1 clas_fds2 &&
702        (null sc_theta1 && null op_stuff1
703         ||
704         eqListBy (tcEqPredX env) sc_theta1 sc_theta2 &&
705         eqListBy eqSig op_stuff1 op_stuff2)
706
707 checkBootDecl (ADataCon dc1) (ADataCon dc2)
708   = pprPanic "checkBootDecl" (ppr dc1)
709
710 checkBootDecl _ _ = False -- probably shouldn't happen
711
712 ----------------
713 missingBootThing thing what
714   = ppr thing <+> ptext (sLit "is exported by the hs-boot file, but not") 
715               <+> text what <+> ptext (sLit "the module")
716
717 bootMisMatch thing boot_decl real_decl
718   = vcat [ppr thing <+> ptext (sLit "has conflicting definitions in the module and its hs-boot file"),
719           ptext (sLit "Main module:") <+> ppr real_decl,
720           ptext (sLit "Boot file:  ") <+> ppr boot_decl]
721
722 instMisMatch inst
723   = hang (ppr inst)
724        2 (ptext (sLit "is defined in the hs-boot file, but not in the module itself"))
725 \end{code}
726
727
728 %************************************************************************
729 %*                                                                      *
730         Type-checking the top level of a module
731 %*                                                                      *
732 %************************************************************************
733
734 tcRnGroup takes a bunch of top-level source-code declarations, and
735  * renames them
736  * gets supporting declarations from interface files
737  * typechecks them
738  * zonks them
739  * and augments the TcGblEnv with the results
740
741 In Template Haskell it may be called repeatedly for each group of
742 declarations.  It expects there to be an incoming TcGblEnv in the
743 monad; it augments it and returns the new TcGblEnv.
744
745 \begin{code}
746 ------------------------------------------------
747 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
748 -- Fails if there are any errors
749 rnTopSrcDecls group
750  = do { -- Rename the source decls (with no shadowing; error on duplicates)
751         (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls False group ;
752
753         -- save the renamed syntax, if we want it
754         let { tcg_env'
755                 | Just grp <- tcg_rn_decls tcg_env
756                   = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
757                 | otherwise
758                    = tcg_env };
759
760                 -- Dump trace of renaming part
761         rnDump (ppr rn_decls) ;
762
763         return (tcg_env', rn_decls)
764    }
765
766 ------------------------------------------------
767 tcTopSrcDecls :: ModDetails -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
768 tcTopSrcDecls boot_details
769         (HsGroup { hs_tyclds = tycl_decls, 
770                    hs_instds = inst_decls,
771                    hs_derivds = deriv_decls,
772                    hs_fords  = foreign_decls,
773                    hs_defds  = default_decls,
774                    hs_ruleds = rule_decls,
775                    hs_valds  = val_binds })
776  = do {         -- Type-check the type and class decls, and all imported decls
777                 -- The latter come in via tycl_decls
778         traceTc (text "Tc2") ;
779
780         tcg_env <- tcTyAndClassDecls boot_details tycl_decls ;
781                 -- If there are any errors, tcTyAndClassDecls fails here
782         
783         setGblEnv tcg_env       $ do {
784                 -- Source-language instances, including derivings,
785                 -- and import the supporting declarations
786         traceTc (text "Tc3") ;
787         (tcg_env, inst_infos, deriv_binds) 
788             <- tcInstDecls1 tycl_decls inst_decls deriv_decls;
789         setGblEnv tcg_env       $ do {
790
791                 -- Foreign import declarations next.  No zonking necessary
792                 -- here; we can tuck them straight into the global environment.
793         traceTc (text "Tc4") ;
794         (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
795         tcExtendGlobalValEnv fi_ids     $ do {
796
797                 -- Default declarations
798         traceTc (text "Tc4a") ;
799         default_tys <- tcDefaults default_decls ;
800         updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
801         
802                 -- Value declarations next
803                 -- We also typecheck any extra binds that came out 
804                 -- of the "deriving" process (deriv_binds)
805         traceTc (text "Tc5") ;
806         (tc_val_binds,   tcl_env) <- tcTopBinds val_binds ;
807         setLclTypeEnv tcl_env   $ do {
808
809                 -- Now GHC-generated derived bindings and generics.
810                 -- Do not generate warnings from compiler-generated code.
811         (tc_deriv_binds, tcl_env) <- discardWarnings $
812                                  tcTopBinds deriv_binds ;
813
814                 -- Second pass over class and instance declarations, 
815         traceTc (text "Tc6") ;
816         (inst_binds, tcl_env)     <- setLclTypeEnv tcl_env $ tcInstDecls2 tycl_decls inst_infos ;
817         showLIE (text "after instDecls2") ;
818
819                 -- Foreign exports
820                 -- They need to be zonked, so we return them
821         traceTc (text "Tc7") ;
822         (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
823
824                 -- Rules
825         rules <- tcRules rule_decls ;
826
827                 -- Wrap up
828         traceTc (text "Tc7a") ;
829         tcg_env <- getGblEnv ;
830         let { all_binds = tc_val_binds   `unionBags`
831                           tc_deriv_binds `unionBags`
832                           inst_binds     `unionBags`
833                           foe_binds  ;
834
835                 -- Extend the GblEnv with the (as yet un-zonked) 
836                 -- bindings, rules, foreign decls
837               tcg_env' = tcg_env {  tcg_binds = tcg_binds tcg_env `unionBags` all_binds,
838                                     tcg_rules = tcg_rules tcg_env ++ rules,
839                                     tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
840         return (tcg_env', tcl_env)
841     }}}}}}
842 \end{code}
843
844
845 %************************************************************************
846 %*                                                                      *
847         Checking for 'main'
848 %*                                                                      *
849 %************************************************************************
850
851 \begin{code}
852 checkMain :: TcM TcGblEnv
853 -- If we are in module Main, check that 'main' is defined.
854 checkMain 
855   = do { tcg_env   <- getGblEnv ;
856          dflags    <- getDOpts ;
857          check_main dflags tcg_env
858     }
859
860 check_main dflags tcg_env
861  | mod /= main_mod
862  = traceTc (text "checkMain not" <+> ppr main_mod <+> ppr mod) >>
863    return tcg_env
864
865  | otherwise
866  = do   { mb_main <- lookupSrcOcc_maybe main_fn
867                 -- Check that 'main' is in scope
868                 -- It might be imported from another module!
869         ; case mb_main of {
870              Nothing -> do { traceTc (text "checkMain fail" <+> ppr main_mod <+> ppr main_fn)
871                            ; complain_no_main   
872                            ; return tcg_env } ;
873              Just main_name -> do
874
875         { traceTc (text "checkMain found" <+> ppr main_mod <+> ppr main_fn)
876         ; let loc = srcLocSpan (getSrcLoc main_name)
877         ; ioTyCon <- tcLookupTyCon ioTyConName
878         ; (main_expr, res_ty) 
879                 <- addErrCtxt mainCtxt    $
880                    withBox liftedTypeKind $ \res_ty -> 
881                    tcMonoExpr (L loc (HsVar main_name)) (mkTyConApp ioTyCon [res_ty])
882
883                 -- See Note [Root-main Id]
884                 -- Construct the binding
885                 --      :Main.main :: IO res_ty = runMainIO res_ty main 
886         ; run_main_id <- tcLookupId runMainIOName
887         ; let { root_main_name =  mkExternalName rootMainKey rOOT_MAIN 
888                                    (mkVarOccFS (fsLit "main")) 
889                                    (getSrcSpan main_name)
890               ; root_main_id = Id.mkExportedLocalId root_main_name 
891                                                     (mkTyConApp ioTyCon [res_ty])
892               ; co  = mkWpTyApps [res_ty]
893               ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) main_expr
894               ; main_bind = noLoc (VarBind root_main_id rhs) }
895
896         ; return (tcg_env { tcg_binds = tcg_binds tcg_env 
897                                         `snocBag` main_bind,
898                             tcg_dus   = tcg_dus tcg_env
899                                         `plusDU` usesOnly (unitFV main_name)
900                         -- Record the use of 'main', so that we don't 
901                         -- complain about it being defined but not used
902                  }) 
903     }}}
904   where
905     mod          = tcg_mod tcg_env
906     main_mod     = mainModIs dflags
907     main_fn      = getMainFun dflags
908
909     complain_no_main | ghcLink dflags == LinkInMemory = return ()
910                      | otherwise = failWithTc noMainMsg
911         -- In interactive mode, don't worry about the absence of 'main'
912         -- In other modes, fail altogether, so that we don't go on
913         -- and complain a second time when processing the export list.
914
915     mainCtxt  = ptext (sLit "When checking the type of the") <+> pp_main_fn
916     noMainMsg = ptext (sLit "The") <+> pp_main_fn
917                 <+> ptext (sLit "is not defined in module") <+> quotes (ppr main_mod)
918     pp_main_fn | main_fn == main_RDR_Unqual = ptext (sLit "function") <+> quotes (ppr main_fn)
919                | otherwise                  = ptext (sLit "main function") <+> quotes (ppr main_fn)
920                
921 \end{code}
922
923 Note [Root-main Id]
924 ~~~~~~~~~~~~~~~~~~~
925 The function that the RTS invokes is always :Main.main, which we call
926 root_main_id.  (Because GHC allows the user to have a module not
927 called Main as the main module, we can't rely on the main function
928 being called "Main.main".  That's why root_main_id has a fixed module
929 ":Main".)  
930
931 This is unusual: it's a LocalId whose Name has a Module from another
932 module.  Tiresomely, we must filter it out again in MkIface, les we
933 get two defns for 'main' in the interface file!
934
935
936 %*********************************************************
937 %*                                                       *
938                 GHCi stuff
939 %*                                                       *
940 %*********************************************************
941
942 \begin{code}
943 #ifdef GHCI
944 setInteractiveContext :: HscEnv -> InteractiveContext -> TcRn a -> TcRn a
945 setInteractiveContext hsc_env icxt thing_inside 
946   = let -- Initialise the tcg_inst_env with instances from all home modules.  
947         -- This mimics the more selective call to hptInstances in tcRnModule.
948         (home_insts, home_fam_insts) = hptInstances hsc_env (\mod -> True)
949     in
950     updGblEnv (\env -> env { 
951         tcg_rdr_env      = ic_rn_gbl_env icxt,
952         tcg_inst_env     = extendInstEnvList    (tcg_inst_env env) home_insts,
953         tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env env) 
954                                                 home_fam_insts 
955       }) $
956
957     tcExtendGhciEnv (ic_tmp_ids icxt) $
958         -- tcExtendGhciEnv does lots: 
959         --   - it extends the local type env (tcl_env) with the given Ids,
960         --   - it extends the local rdr env (tcl_rdr) with the Names from 
961         --     the given Ids
962         --   - it adds the free tyvars of the Ids to the tcl_tyvars
963         --     set.
964         --
965         -- later ids in ic_tmp_ids must shadow earlier ones with the same
966         -- OccName, and tcExtendIdEnv implements this behaviour.
967
968     do  { traceTc (text "setIC" <+> ppr (ic_tmp_ids icxt))
969         ; thing_inside }
970 \end{code}
971
972
973 \begin{code}
974 tcRnStmt :: HscEnv
975          -> InteractiveContext
976          -> LStmt RdrName
977          -> IO (Messages, Maybe ([Id], LHsExpr Id))
978                 -- The returned [Id] is the list of new Ids bound by
979                 -- this statement.  It can be used to extend the
980                 -- InteractiveContext via extendInteractiveContext.
981                 --
982                 -- The returned TypecheckedHsExpr is of type IO [ () ],
983                 -- a list of the bound values, coerced to ().
984
985 tcRnStmt hsc_env ictxt rdr_stmt
986   = initTcPrintErrors hsc_env iNTERACTIVE $ 
987     setInteractiveContext hsc_env ictxt $ do {
988
989     -- Rename; use CmdLineMode because tcRnStmt is only used interactively
990     (([rn_stmt], _), fvs) <- rnStmts DoExpr [rdr_stmt] (return ((), emptyFVs)) ;
991     traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
992     failIfErrsM ;
993     rnDump (ppr rn_stmt) ;
994     
995     -- The real work is done here
996     (bound_ids, tc_expr) <- mkPlan rn_stmt ;
997     zonked_expr <- zonkTopLExpr tc_expr ;
998     zonked_ids  <- zonkTopBndrs bound_ids ;
999     
1000         -- None of the Ids should be of unboxed type, because we
1001         -- cast them all to HValues in the end!
1002     mapM bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
1003
1004     traceTc (text "tcs 1") ;
1005     let { global_ids = map globaliseAndTidy zonked_ids } ;
1006     
1007 {- ---------------------------------------------
1008    At one stage I removed any shadowed bindings from the type_env;
1009    they are inaccessible but might, I suppose, cause a space leak if we leave them there.
1010    However, with Template Haskell they aren't necessarily inaccessible.  Consider this
1011    GHCi session
1012          Prelude> let f n = n * 2 :: Int
1013          Prelude> fName <- runQ [| f |]
1014          Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1015          14
1016          Prelude> let f n = n * 3 :: Int
1017          Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1018    In the last line we use 'fName', which resolves to the *first* 'f'
1019    in scope. If we delete it from the type env, GHCi crashes because
1020    it doesn't expect that.
1021  
1022    Hence this code is commented out
1023
1024 -------------------------------------------------- -}
1025
1026     dumpOptTcRn Opt_D_dump_tc 
1027         (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
1028                text "Typechecked expr" <+> ppr zonked_expr]) ;
1029
1030     return (global_ids, zonked_expr)
1031     }
1032   where
1033     bad_unboxed id = addErr (sep [ptext (sLit "GHCi can't bind a variable of unlifted type:"),
1034                                   nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
1035
1036 globaliseAndTidy :: Id -> Id
1037 globaliseAndTidy id     -- Note [Interactively-bound Ids in GHCi]
1038   = Id.setIdType (globaliseId VanillaGlobal id) tidy_type
1039   where
1040     tidy_type = tidyTopType (idType id)
1041 \end{code}
1042
1043 Note [Interactively-bound Ids in GHCi]
1044 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1045 The Ids bound by previous Stmts in Template Haskell are currently
1046         a) GlobalIds
1047         b) with an Internal Name (not External)
1048         c) and a tidied type
1049
1050  (a) They must be GlobalIds (not LocalIds) otherwise when we come to
1051      compile an expression using these ids later, the byte code
1052      generator will consider the occurrences to be free rather than
1053      global.
1054
1055  (b) They retain their Internal names becuase we don't have a suitable
1056      Module to name them with.  We could revisit this choice.
1057
1058  (c) Their types are tidied.  This is important, because :info may ask
1059      to look at them, and :info expects the things it looks up to have
1060      tidy types
1061         
1062
1063 --------------------------------------------------------------------------
1064                 Typechecking Stmts in GHCi
1065
1066 Here is the grand plan, implemented in tcUserStmt
1067
1068         What you type                   The IO [HValue] that hscStmt returns
1069         -------------                   ------------------------------------
1070         let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
1071                                         bindings: [x,y,...]
1072
1073         pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
1074                                         bindings: [x,y,...]
1075
1076         expr (of IO type)       ==>     expr >>= \ it -> return [coerce HVal it]
1077           [NB: result not printed]      bindings: [it]
1078           
1079         expr (of non-IO type,   ==>     let it = expr in print it >> return [coerce HVal it]
1080           result showable)              bindings: [it]
1081
1082         expr (of non-IO type, 
1083           result not showable)  ==>     error
1084
1085
1086 \begin{code}
1087 ---------------------------
1088 type PlanResult = ([Id], LHsExpr Id)
1089 type Plan = TcM PlanResult
1090
1091 runPlans :: [Plan] -> TcM PlanResult
1092 -- Try the plans in order.  If one fails (by raising an exn), try the next.
1093 -- If one succeeds, take it.
1094 runPlans []     = panic "runPlans"
1095 runPlans [p]    = p
1096 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
1097
1098 --------------------
1099 mkPlan :: LStmt Name -> TcM PlanResult
1100 mkPlan (L loc (ExprStmt expr _ _))      -- An expression typed at the prompt 
1101   = do  { uniq <- newUnique             -- is treated very specially
1102         ; let fresh_it  = itName uniq
1103               the_bind  = L loc $ mkFunBind (L loc fresh_it) matches
1104               matches   = [mkMatch [] expr emptyLocalBinds]
1105               let_stmt  = L loc $ LetStmt (HsValBinds (ValBindsOut [(NonRecursive,unitBag the_bind)] []))
1106               bind_stmt = L loc $ BindStmt (nlVarPat fresh_it) expr
1107                                            (HsVar bindIOName) noSyntaxExpr 
1108               print_it  = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar fresh_it))
1109                                            (HsVar thenIOName) placeHolderType
1110
1111         -- The plans are:
1112         --      [it <- e; print it]     but not if it::()
1113         --      [it <- e]               
1114         --      [let it = e; print it]  
1115         ; runPlans [    -- Plan A
1116                     do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
1117                        ; it_ty <- zonkTcType (idType it_id)
1118                        ; when (isUnitTy it_ty) failM
1119                        ; return stuff },
1120
1121                         -- Plan B; a naked bind statment
1122                     tcGhciStmts [bind_stmt],    
1123
1124                         -- Plan C; check that the let-binding is typeable all by itself.
1125                         -- If not, fail; if so, try to print it.
1126                         -- The two-step process avoids getting two errors: one from
1127                         -- the expression itself, and one from the 'print it' part
1128                         -- This two-step story is very clunky, alas
1129                     do { checkNoErrs (tcGhciStmts [let_stmt]) 
1130                                 --- checkNoErrs defeats the error recovery of let-bindings
1131                        ; tcGhciStmts [let_stmt, print_it] }
1132           ]}
1133
1134 mkPlan stmt@(L loc (BindStmt {}))
1135   | [L _ v] <- collectLStmtBinders stmt         -- One binder, for a bind stmt 
1136   = do  { let print_v  = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
1137                                            (HsVar thenIOName) placeHolderType
1138
1139         ; print_bind_result <- doptM Opt_PrintBindResult
1140         ; let print_plan = do
1141                   { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
1142                   ; v_ty <- zonkTcType (idType v_id)
1143                   ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM
1144                   ; return stuff }
1145
1146         -- The plans are:
1147         --      [stmt; print v]         but not if v::()
1148         --      [stmt]
1149         ; runPlans ((if print_bind_result then [print_plan] else []) ++
1150                     [tcGhciStmts [stmt]])
1151         }
1152
1153 mkPlan stmt
1154   = tcGhciStmts [stmt]
1155
1156 ---------------------------
1157 tcGhciStmts :: [LStmt Name] -> TcM PlanResult
1158 tcGhciStmts stmts
1159  = do { ioTyCon <- tcLookupTyCon ioTyConName ;
1160         ret_id  <- tcLookupId returnIOName ;            -- return @ IO
1161         let {
1162             ret_ty    = mkListTy unitTy ;
1163             io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
1164             tc_io_stmts stmts = tcStmts DoExpr tcDoStmt stmts io_ret_ty ;
1165
1166             names = map unLoc (collectLStmtsBinders stmts) ;
1167
1168                 -- mk_return builds the expression
1169                 --      returnIO @ [()] [coerce () x, ..,  coerce () z]
1170                 --
1171                 -- Despite the inconvenience of building the type applications etc,
1172                 -- this *has* to be done in type-annotated post-typecheck form
1173                 -- because we are going to return a list of *polymorphic* values
1174                 -- coerced to type (). If we built a *source* stmt
1175                 --      return [coerce x, ..., coerce z]
1176                 -- then the type checker would instantiate x..z, and we wouldn't
1177                 -- get their *polymorphic* values.  (And we'd get ambiguity errs
1178                 -- if they were overloaded, since they aren't applied to anything.)
1179             mk_return ids = nlHsApp (nlHsTyApp ret_id [ret_ty]) 
1180                                     (noLoc $ ExplicitList unitTy (map mk_item ids)) ;
1181             mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
1182                                  (nlHsVar id) 
1183          } ;
1184
1185         -- OK, we're ready to typecheck the stmts
1186         traceTc (text "TcRnDriver.tcGhciStmts: tc stmts") ;
1187         ((tc_stmts, ids), lie) <- getLIE $ tc_io_stmts stmts $ \ _ ->
1188                                            mapM tcLookupId names ;
1189                                         -- Look up the names right in the middle,
1190                                         -- where they will all be in scope
1191
1192         -- Simplify the context
1193         traceTc (text "TcRnDriver.tcGhciStmts: simplify ctxt") ;
1194         const_binds <- checkNoErrs (tcSimplifyInteractive lie) ;
1195                 -- checkNoErrs ensures that the plan fails if context redn fails
1196
1197         traceTc (text "TcRnDriver.tcGhciStmts: done") ;
1198         return (ids, mkHsDictLet const_binds $
1199                      noLoc (HsDo DoExpr tc_stmts (mk_return ids) io_ret_ty))
1200     }
1201 \end{code}
1202
1203
1204 tcRnExpr just finds the type of an expression
1205
1206 \begin{code}
1207 tcRnExpr :: HscEnv
1208          -> InteractiveContext
1209          -> LHsExpr RdrName
1210          -> IO (Messages, Maybe Type)
1211 tcRnExpr hsc_env ictxt rdr_expr
1212   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1213     setInteractiveContext hsc_env ictxt $ do {
1214
1215     (rn_expr, fvs) <- rnLExpr rdr_expr ;
1216     failIfErrsM ;
1217
1218         -- Now typecheck the expression; 
1219         -- it might have a rank-2 type (e.g. :t runST)
1220     ((tc_expr, res_ty), lie)       <- getLIE (tcInferRho rn_expr) ;
1221     ((qtvs, dict_insts, _), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie)  ;
1222     tcSimplifyInteractive lie_top ;
1223
1224     let { all_expr_ty = mkForAllTys qtvs $
1225                         mkFunTys (map (idType . instToId) dict_insts)   $
1226                         res_ty } ;
1227     zonkTcType all_expr_ty
1228     }
1229   where
1230     smpl_doc = ptext (sLit "main expression")
1231 \end{code}
1232
1233 tcRnType just finds the kind of a type
1234
1235 \begin{code}
1236 tcRnType :: HscEnv
1237          -> InteractiveContext
1238          -> LHsType RdrName
1239          -> IO (Messages, Maybe Kind)
1240 tcRnType hsc_env ictxt rdr_type
1241   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1242     setInteractiveContext hsc_env ictxt $ do {
1243
1244     rn_type <- rnLHsType doc rdr_type ;
1245     failIfErrsM ;
1246
1247         -- Now kind-check the type
1248     (ty', kind) <- kcHsType rn_type ;
1249     return kind
1250     }
1251   where
1252     doc = ptext (sLit "In GHCi input")
1253
1254 #endif /* GHCi */
1255 \end{code}
1256
1257
1258 %************************************************************************
1259 %*                                                                      *
1260         More GHCi stuff, to do with browsing and getting info
1261 %*                                                                      *
1262 %************************************************************************
1263
1264 \begin{code}
1265 #ifdef GHCI
1266 -- | ASSUMES that the module is either in the 'HomePackageTable' or is
1267 -- a package module with an interface on disk.  If neither of these is
1268 -- true, then the result will be an error indicating the interface
1269 -- could not be found.
1270 getModuleExports :: HscEnv -> Module -> IO (Messages, Maybe [AvailInfo])
1271 getModuleExports hsc_env mod
1272   = let
1273       ic        = hsc_IC hsc_env
1274       checkMods = ic_toplev_scope ic ++ ic_exports ic
1275     in
1276     initTc hsc_env HsSrcFile False iNTERACTIVE (tcGetModuleExports mod checkMods)
1277
1278 -- Get the export avail info and also load all orphan and family-instance
1279 -- modules.  Finally, check that the family instances of all modules in the
1280 -- interactive context are consistent (these modules are in the second
1281 -- argument).
1282 tcGetModuleExports :: Module -> [Module] -> TcM [AvailInfo]
1283 tcGetModuleExports mod directlyImpMods
1284   = do { let doc = ptext (sLit "context for compiling statements")
1285        ; iface <- initIfaceTcRn $ loadSysInterface doc mod
1286
1287                 -- Load any orphan-module and family instance-module
1288                 -- interfaces, so their instances are visible.
1289        ; loadOrphanModules (dep_orphs (mi_deps iface)) False 
1290        ; loadOrphanModules (dep_finsts (mi_deps iface)) True
1291
1292                 -- Check that the family instances of all directly loaded
1293                 -- modules are consistent.
1294        ; checkFamInstConsistency (dep_finsts (mi_deps iface)) directlyImpMods
1295
1296        ; ifaceExportNames (mi_exports iface)
1297        }
1298
1299 tcRnLookupRdrName :: HscEnv -> RdrName -> IO (Messages, Maybe [Name])
1300 tcRnLookupRdrName hsc_env rdr_name 
1301   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1302     setInteractiveContext hsc_env (hsc_IC hsc_env) $ 
1303     lookup_rdr_name rdr_name
1304
1305 lookup_rdr_name rdr_name = do {
1306         -- If the identifier is a constructor (begins with an
1307         -- upper-case letter), then we need to consider both
1308         -- constructor and type class identifiers.
1309     let { rdr_names = dataTcOccs rdr_name } ;
1310
1311         -- results :: [Either Messages Name]
1312     results <- mapM (tryTcErrs . lookupOccRn) rdr_names ;
1313
1314     traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)]);
1315         -- The successful lookups will be (Just name)
1316     let { (warns_s, good_names) = unzip [ (msgs, name) 
1317                                         | (msgs, Just name) <- results] ;
1318           errs_s = [msgs | (msgs, Nothing) <- results] } ;
1319
1320         -- Fail if nothing good happened, else add warnings
1321     if null good_names then
1322                 -- No lookup succeeded, so
1323                 -- pick the first error message and report it
1324                 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
1325                 --       while the other is "X is not in scope", 
1326                 --       we definitely want the former; but we might pick the latter
1327         do { addMessages (head errs_s) ; failM }
1328       else                      -- Add deprecation warnings
1329         mapM_ addMessages warns_s ;
1330     
1331     return good_names
1332  }
1333
1334 tcRnLookupName :: HscEnv -> Name -> IO (Messages, Maybe TyThing)
1335 tcRnLookupName hsc_env name
1336   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1337     setInteractiveContext hsc_env (hsc_IC hsc_env) $
1338     tcRnLookupName' name
1339
1340 -- To look up a name we have to look in the local environment (tcl_lcl)
1341 -- as well as the global environment, which is what tcLookup does. 
1342 -- But we also want a TyThing, so we have to convert:
1343
1344 tcRnLookupName' :: Name -> TcRn TyThing
1345 tcRnLookupName' name = do
1346    tcthing <- tcLookup name
1347    case tcthing of
1348      AGlobal thing    -> return thing
1349      ATcId{tct_id=id} -> return (AnId id)
1350      _ -> panic "tcRnLookupName'"
1351
1352 tcRnGetInfo :: HscEnv
1353             -> Name
1354             -> IO (Messages, Maybe (TyThing, Fixity, [Instance]))
1355
1356 -- Used to implemnent :info in GHCi
1357 --
1358 -- Look up a RdrName and return all the TyThings it might be
1359 -- A capitalised RdrName is given to us in the DataName namespace,
1360 -- but we want to treat it as *both* a data constructor 
1361 --  *and* as a type or class constructor; 
1362 -- hence the call to dataTcOccs, and we return up to two results
1363 tcRnGetInfo hsc_env name
1364   = initTcPrintErrors hsc_env iNTERACTIVE $ 
1365     let ictxt = hsc_IC hsc_env in
1366     setInteractiveContext hsc_env ictxt $ do
1367
1368         -- Load the interface for all unqualified types and classes
1369         -- That way we will find all the instance declarations
1370         -- (Packages have not orphan modules, and we assume that
1371         --  in the home package all relevant modules are loaded.)
1372     loadUnqualIfaces ictxt
1373
1374     thing  <- tcRnLookupName' name
1375     fixity <- lookupFixityRn name
1376     ispecs <- lookupInsts thing
1377     return (thing, fixity, ispecs)
1378
1379 lookupInsts :: TyThing -> TcM [Instance]
1380 lookupInsts (AClass cls)
1381   = do  { inst_envs <- tcGetInstEnvs
1382         ; return (classInstances inst_envs cls) }
1383
1384 lookupInsts (ATyCon tc)
1385   = do  { eps <- getEps -- Load all instances for all classes that are
1386                         -- in the type environment (which are all the ones
1387                         -- we've seen in any interface file so far)
1388         ; (pkg_ie, home_ie) <- tcGetInstEnvs    -- Search all
1389         ; return [ ispec
1390                  | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
1391                  , let dfun = instanceDFunId ispec
1392                  , relevant dfun ] } 
1393   where
1394     relevant df = tc_name `elemNameSet` tyClsNamesOfDFunHead (idType df)
1395     tc_name     = tyConName tc            
1396
1397 lookupInsts other = return []
1398
1399 loadUnqualIfaces :: InteractiveContext -> TcM ()
1400 -- Load the home module for everything that is in scope unqualified
1401 -- This is so that we can accurately report the instances for 
1402 -- something
1403 loadUnqualIfaces ictxt
1404   = initIfaceTcRn $
1405     mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
1406   where
1407     unqual_mods = [ nameModule name
1408                   | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt),
1409                     let name = gre_name gre,
1410                     not (isInternalName name),
1411                     isTcOcc (nameOccName name),  -- Types and classes only
1412                     unQualOK gre ]               -- In scope unqualified
1413     doc = ptext (sLit "Need interface for module whose export(s) are in scope unqualified")
1414 #endif /* GHCI */
1415 \end{code}
1416
1417 %************************************************************************
1418 %*                                                                      *
1419                 Degugging output
1420 %*                                                                      *
1421 %************************************************************************
1422
1423 \begin{code}
1424 rnDump :: SDoc -> TcRn ()
1425 -- Dump, with a banner, if -ddump-rn
1426 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
1427
1428 tcDump :: TcGblEnv -> TcRn ()
1429 tcDump env
1430  = do { dflags <- getDOpts ;
1431
1432         -- Dump short output if -ddump-types or -ddump-tc
1433         when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1434              (dumpTcRn short_dump) ;
1435
1436         -- Dump bindings if -ddump-tc
1437         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1438    }
1439   where
1440     short_dump = pprTcGblEnv env
1441     full_dump  = pprLHsBinds (tcg_binds env)
1442         -- NB: foreign x-d's have undefined's in their types; 
1443         --     hence can't show the tc_fords
1444
1445 tcCoreDump mod_guts
1446  = do { dflags <- getDOpts ;
1447         when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1448              (dumpTcRn (pprModGuts mod_guts)) ;
1449
1450         -- Dump bindings if -ddump-tc
1451         dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1452   where
1453     full_dump = pprCoreBindings (mg_binds mod_guts)
1454
1455 -- It's unpleasant having both pprModGuts and pprModDetails here
1456 pprTcGblEnv :: TcGblEnv -> SDoc
1457 pprTcGblEnv (TcGblEnv { tcg_type_env  = type_env, 
1458                         tcg_insts     = insts, 
1459                         tcg_fam_insts = fam_insts, 
1460                         tcg_rules     = rules,
1461                         tcg_imports   = imports })
1462   = vcat [ ppr_types insts type_env
1463          , ppr_tycons fam_insts type_env
1464          , ppr_insts insts
1465          , ppr_fam_insts fam_insts
1466          , vcat (map ppr rules)
1467          , ppr_gen_tycons (typeEnvTyCons type_env)
1468          , ptext (sLit "Dependent modules:") <+> 
1469                 ppr (sortBy cmp_mp $ eltsUFM (imp_dep_mods imports))
1470          , ptext (sLit "Dependent packages:") <+> 
1471                 ppr (sortBy stablePackageIdCmp $ imp_dep_pkgs imports)]
1472   where         -- The two uses of sortBy are just to reduce unnecessary
1473                 -- wobbling in testsuite output
1474     cmp_mp (mod_name1, is_boot1) (mod_name2, is_boot2)
1475         = (mod_name1 `stableModuleNameCmp` mod_name2)
1476                   `thenCmp`     
1477           (is_boot1 `compare` is_boot2)
1478
1479 pprModGuts :: ModGuts -> SDoc
1480 pprModGuts (ModGuts { mg_types = type_env,
1481                       mg_rules = rules })
1482   = vcat [ ppr_types [] type_env,
1483            ppr_rules rules ]
1484
1485 ppr_types :: [Instance] -> TypeEnv -> SDoc
1486 ppr_types insts type_env
1487   = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1488   where
1489     dfun_ids = map instanceDFunId insts
1490     ids = [id | id <- typeEnvIds type_env, want_sig id]
1491     want_sig id | opt_PprStyle_Debug = True
1492                 | otherwise          = isLocalId id && 
1493                                        isExternalName (idName id) && 
1494                                        not (id `elem` dfun_ids)
1495         -- isLocalId ignores data constructors, records selectors etc.
1496         -- The isExternalName ignores local dictionary and method bindings
1497         -- that the type checker has invented.  Top-level user-defined things 
1498         -- have External names.
1499
1500 ppr_tycons :: [FamInst] -> TypeEnv -> SDoc
1501 ppr_tycons fam_insts type_env
1502   = text "TYPE CONSTRUCTORS" $$ nest 4 (ppr_tydecls tycons)
1503   where
1504     fi_tycons = map famInstTyCon fam_insts
1505     tycons = [tycon | tycon <- typeEnvTyCons type_env, want_tycon tycon]
1506     want_tycon tycon | opt_PprStyle_Debug = True
1507                      | otherwise          = not (isImplicitTyCon tycon) &&
1508                                             isExternalName (tyConName tycon) &&
1509                                             not (tycon `elem` fi_tycons)
1510
1511 ppr_insts :: [Instance] -> SDoc
1512 ppr_insts []     = empty
1513 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
1514
1515 ppr_fam_insts :: [FamInst] -> SDoc
1516 ppr_fam_insts []        = empty
1517 ppr_fam_insts fam_insts = 
1518   text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
1519
1520 ppr_sigs :: [Var] -> SDoc
1521 ppr_sigs ids
1522         -- Print type signatures; sort by OccName 
1523   = vcat (map ppr_sig (sortLe le_sig ids))
1524   where
1525     le_sig id1 id2 = getOccName id1 <= getOccName id2
1526     ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1527
1528 ppr_tydecls :: [TyCon] -> SDoc
1529 ppr_tydecls tycons
1530         -- Print type constructor info; sort by OccName 
1531   = vcat (map ppr_tycon (sortLe le_sig tycons))
1532   where
1533     le_sig tycon1 tycon2 = getOccName tycon1 <= getOccName tycon2
1534     ppr_tycon tycon 
1535       | isCoercionTyCon tycon = ptext (sLit "coercion") <+> ppr tycon
1536       | otherwise             = ppr (tyThingToIfaceDecl (ATyCon tycon))
1537
1538 ppr_rules :: [CoreRule] -> SDoc
1539 ppr_rules [] = empty
1540 ppr_rules rs = vcat [ptext (sLit "{-# RULES"),
1541                       nest 4 (pprRules rs),
1542                       ptext (sLit "#-}")]
1543
1544 ppr_gen_tycons []  = empty
1545 ppr_gen_tycons tcs = vcat [ptext (sLit "Tycons with generics:"),
1546                            nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]
1547 \end{code}