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