2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
9 mkExportEnv, getModuleContents, tcRnStmt,
10 tcRnGetInfo, tcRnExpr, tcRnType,
17 #include "HsVersions.h"
20 import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
23 import CmdLineOpts ( DynFlag(..), opt_PprStyle_Debug, dopt )
24 import Packages ( moduleToPackageConfig, mkPackageId, package,
26 import DriverState ( v_MainModIs, v_MainFunIs )
27 import HsSyn ( HsModule(..), HsExtCore(..), HsGroup(..), LHsDecl, SpliceDecl(..), HsBind(..),
28 nlHsApp, nlHsVar, pprLHsBinds )
29 import RdrHsSyn ( findSplice )
31 import PrelNames ( runIOName, rootMainName, mAIN,
33 import RdrName ( RdrName, mkRdrUnqual, emptyGlobalRdrEnv,
35 import TcHsSyn ( zonkTopDecls )
36 import TcExpr ( tcInferRho )
38 import TcType ( tidyTopType, tcEqType, mkTyVarTys, substTyWith )
39 import Inst ( showLIE )
40 import TcBinds ( tcTopBinds )
41 import TcDefaults ( tcDefaults )
42 import TcEnv ( tcExtendGlobalValEnv )
43 import TcRules ( tcRules )
44 import TcForeign ( tcForeignImports, tcForeignExports )
45 import TcInstDcls ( tcInstDecls1, tcInstDecls2 )
46 import TcIface ( tcExtCoreBindings )
47 import TcSimplify ( tcSimplifyTop )
48 import TcTyClsDecls ( tcTyAndClassDecls )
49 import LoadIface ( loadOrphanModules, loadHiBootInterface )
50 import RnNames ( importsFromLocalDecls, rnImports, exportsFromAvail,
51 reportUnusedNames, reportDeprecations )
52 import RnEnv ( lookupSrcOcc_maybe )
53 import RnSource ( rnSrcDecls, rnTyClDecls, checkModDeprec )
54 import PprCore ( pprIdRules, pprCoreBindings )
55 import CoreSyn ( IdCoreRule, bindersOfBinds )
56 import DataCon ( dataConWrapId )
57 import ErrUtils ( Messages, mkDumpDoc, showPass )
58 import Id ( mkExportedLocalId, isLocalId, idName, idType )
60 import Module ( mkModule, moduleEnvElts )
61 import OccName ( mkVarOcc )
62 import Name ( Name, isExternalName, getSrcLoc, getOccName )
64 import TyCon ( tyConHasGenerics, isSynTyCon, getSynTyConDefn, tyConKind )
65 import SrcLoc ( srcLocSpan, Located(..), noLoc )
67 import HscTypes ( ModGuts(..), HscEnv(..), ExternalPackageState(..),
68 GhciMode(..), noDependencies,
69 Deprecs( NoDeprecs ), plusDeprecs,
70 ForeignStubs(NoStubs), TyThing(..),
71 TypeEnv, lookupTypeEnv,
72 extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
76 import HsSyn ( HsStmtContext(..), Stmt(..), HsExpr(..), HsBindGroup(..),
77 LStmt, LHsExpr, LHsType, mkMatchGroup,
78 collectStmtsBinders, mkSimpleMatch, placeHolderType,
79 nlLetStmt, nlExprStmt, nlBindStmt, nlResultStmt, nlVarPat )
80 import RdrName ( GlobalRdrEnv, mkGlobalRdrEnv, GlobalRdrElt(..),
81 Provenance(..), ImportSpec(..),
82 lookupLocalRdrEnv, extendLocalRdrEnv )
83 import RnSource ( addTcgDUs )
84 import TcHsSyn ( mkHsLet, zonkTopLExpr, zonkTopBndrs )
85 import TcHsType ( kcHsType )
86 import TcExpr ( tcCheckRho )
87 import TcIface ( loadImportedInsts )
88 import TcMType ( zonkTcType, zonkQuantifiedTyVar )
89 import TcUnify ( unifyTyConApp )
90 import TcMatches ( tcStmtsAndThen, TcStmtCtxt(..) )
91 import TcSimplify ( tcSimplifyInteractive, tcSimplifyInfer )
92 import TcType ( Type, mkForAllTys, mkFunTys, mkTyConApp, tyVarsOfType,
93 isUnLiftedType, tyClsNamesOfDFunHead )
94 import TcEnv ( tcLookupTyCon, tcLookupId, tcLookupGlobal )
95 import RnTypes ( rnLHsType )
96 import Inst ( tcStdSyntaxName, tcGetInstEnvs )
97 import InstEnv ( DFunId, classInstances, instEnvElts )
98 import RnExpr ( rnStmts, rnLExpr )
99 import RnNames ( exportsToAvails )
100 import LoadIface ( loadSrcInterface )
101 import IfaceSyn ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..),
102 IfaceExtName(..), IfaceConDecls(..), IfaceInst(..),
103 tyThingToIfaceDecl, dfunToIfaceInst )
104 import RnEnv ( lookupOccRn, dataTcOccs, lookupFixityRn )
105 import Id ( Id, isImplicitId, globalIdDetails )
106 import MkId ( unsafeCoerceId )
107 import DataCon ( dataConTyCon )
108 import TyCon ( tyConName )
109 import TysWiredIn ( mkListTy, unitTy )
110 import IdInfo ( GlobalIdDetails(..) )
111 import SrcLoc ( interactiveSrcLoc, unLoc )
113 import Var ( globaliseId )
114 import Name ( nameOccName, nameModule )
115 import NameEnv ( delListFromNameEnv )
116 import PrelNames ( iNTERACTIVE, ioTyConName, printName, monadNames, itName, returnIOName )
117 import Module ( Module, lookupModuleEnv )
118 import HscTypes ( InteractiveContext(..), ExternalPackageState( eps_PTE ),
119 HomeModInfo(..), typeEnvElts, typeEnvClasses,
120 availNames, icPrintUnqual,
121 ModDetails(..), Dependencies(..) )
122 import BasicTypes ( RecFlag(..), Fixity )
123 import Bag ( unitBag )
124 import ListSetOps ( removeDups )
125 import Panic ( ghcError, GhcException(..) )
126 import SrcLoc ( SrcLoc )
129 import FastString ( mkFastString )
130 import Util ( sortLe )
131 import Bag ( unionBags, snocBag )
133 import Maybe ( isJust )
138 %************************************************************************
140 Typecheck and rename a module
142 %************************************************************************
147 -> Located (HsModule RdrName)
148 -> IO (Messages, Maybe TcGblEnv)
150 tcRnModule hsc_env (L loc (HsModule maybe_mod export_ies
151 import_decls local_decls mod_deprec))
152 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
154 let { this_mod = case maybe_mod of
156 -- 'module M where' is omitted
157 Just (L _ mod) -> mod } ;
160 initTc hsc_env this_mod $
163 checkForPackageModule (hsc_dflags hsc_env) this_mod;
165 -- Deal with imports; sets tcg_rdr_env, tcg_imports
166 (rdr_env, imports) <- rnImports import_decls ;
168 -- Record boot-file info in the EPS, so that it's
169 -- visible to loadHiBootInterface in tcRnSrcDecls,
170 -- and any other incrementally-performed imports
171 updateEps_ (\eps -> eps { eps_is_boot = imp_dep_mods imports }) ;
173 -- Update the gbl env
174 updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
175 tcg_imports = tcg_imports gbl `plusImportAvails` imports })
177 traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
178 -- Fail if there are any errors so far
179 -- The error printing (if needed) takes advantage
180 -- of the tcg_env we have now set
183 -- Load any orphan-module interfaces, so that
184 -- their rules and instance decls will be found
185 loadOrphanModules (imp_orphs imports) ;
187 traceRn (text "rn1a") ;
188 -- Rename and type check the declarations
189 tcg_env <- tcRnSrcDecls local_decls ;
190 setGblEnv tcg_env $ do {
192 traceRn (text "rn3") ;
194 -- Report the use of any deprecated things
195 -- We do this before processsing the export list so
196 -- that we don't bleat about re-exporting a deprecated
197 -- thing (especially via 'module Foo' export item)
198 -- Only uses in the body of the module are complained about
199 reportDeprecations tcg_env ;
201 -- Process the export list
202 exports <- exportsFromAvail (isJust maybe_mod) export_ies ;
204 -- Check whether the entire module is deprecated
205 -- This happens only once per module
206 let { mod_deprecs = checkModDeprec mod_deprec } ;
208 -- Add exports and deprecations to envt
209 let { final_env = tcg_env { tcg_exports = exports,
210 tcg_dus = tcg_dus tcg_env `plusDU` usesOnly exports,
211 tcg_deprecs = tcg_deprecs tcg_env `plusDeprecs`
213 -- A module deprecation over-rides the earlier ones
216 -- Report unused names
217 reportUnusedNames final_env ;
219 -- Dump output and return
224 -- This is really a sanity check that the user has given -package-name
225 -- if necessary. -package-name is only necessary when the package database
226 -- already contains the current package, because then we can't tell
227 -- whether a given module is in the current package or not, without knowing
228 -- the name of the current package.
229 checkForPackageModule dflags this_mod
230 | not (isHomeModule dflags this_mod),
231 Just (pkg,_) <- moduleToPackageConfig dflags this_mod =
233 ppr_pkg = ppr (mkPackageId (package pkg))
235 addErr (ptext SLIT("Module") <+> quotes (ppr this_mod) <+>
236 ptext SLIT("is a member of package") <+> ppr_pkg <> char '.' $$
237 ptext SLIT("To compile this module, please use -ignore-package") <+> ppr_pkg <> char '.')
238 | otherwise = return ()
242 %************************************************************************
244 Type-checking external-core modules
246 %************************************************************************
249 tcRnExtCore :: HscEnv
251 -> IO (Messages, Maybe ModGuts)
252 -- Nothing => some error occurred
254 tcRnExtCore hsc_env (HsExtCore this_mod decls src_binds)
255 -- The decls are IfaceDecls; all names are original names
256 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
258 initTc hsc_env this_mod $ do {
260 let { ldecls = map noLoc decls } ;
262 -- Deal with the type declarations; first bring their stuff
263 -- into scope, then rname them, then type check them
264 (rdr_env, imports) <- importsFromLocalDecls (mkFakeGroup ldecls) ;
266 updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv` tcg_rdr_env gbl,
267 tcg_imports = imports `plusImportAvails` tcg_imports gbl })
270 rn_decls <- rnTyClDecls ldecls ;
273 -- Dump trace of renaming part
274 rnDump (ppr rn_decls) ;
276 -- Typecheck them all together so that
277 -- any mutually recursive types are done right
278 tcg_env <- checkNoErrs (tcTyAndClassDecls [{- no boot names -}] rn_decls) ;
279 -- Make the new type env available to stuff slurped from interface files
281 setGblEnv tcg_env $ do {
283 -- Now the core bindings
284 core_binds <- initIfaceExtCore (tcExtCoreBindings this_mod src_binds) ;
288 bndrs = bindersOfBinds core_binds ;
289 my_exports = mkNameSet (map idName bndrs) ;
290 -- ToDo: export the data types also?
292 final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
294 mod_guts = ModGuts { mg_module = this_mod,
295 mg_usages = [], -- ToDo: compute usage
296 mg_dir_imps = [], -- ??
297 mg_deps = noDependencies, -- ??
298 mg_exports = my_exports,
299 mg_types = final_type_env,
300 mg_insts = tcg_insts tcg_env,
302 mg_binds = core_binds,
305 mg_rdr_env = emptyGlobalRdrEnv,
306 mg_fix_env = emptyFixityEnv,
307 mg_deprecs = NoDeprecs,
311 tcCoreDump mod_guts ;
316 mkFakeGroup decls -- Rather clumsy; lots of unused fields
317 = HsGroup { hs_tyclds = decls, -- This is the one we want
318 hs_valds = [], hs_fords = [],
319 hs_instds = [], hs_fixds = [], hs_depds = [],
320 hs_ruleds = [], hs_defds = [] }
324 %************************************************************************
326 Type-checking the top level of a module
328 %************************************************************************
331 tcRnSrcDecls :: [LHsDecl RdrName] -> TcM TcGblEnv
332 -- Returns the variables free in the decls
333 -- Reason: solely to report unused imports and bindings
335 = do { boot_names <- loadHiBootInterface ;
337 -- Do all the declarations
338 (tc_envs, lie) <- getLIE (tc_rn_src_decls boot_names decls) ;
340 -- tcSimplifyTop deals with constant or ambiguous InstIds.
341 -- How could there be ambiguous ones? They can only arise if a
342 -- top-level decl falls under the monomorphism
343 -- restriction, and no subsequent decl instantiates its
344 -- type. (Usually, ambiguous type variables are resolved
345 -- during the generalisation step.)
346 traceTc (text "Tc8") ;
347 inst_binds <- setEnvs tc_envs (tcSimplifyTop lie) ;
348 -- Setting the global env exposes the instances to tcSimplifyTop
349 -- Setting the local env exposes the local Ids to tcSimplifyTop,
350 -- so that we get better error messages (monomorphism restriction)
352 -- Backsubstitution. This must be done last.
353 -- Even tcSimplifyTop may do some unification.
354 traceTc (text "Tc9") ;
355 let { (tcg_env, _) = tc_envs ;
356 TcGblEnv { tcg_type_env = type_env, tcg_binds = binds,
357 tcg_rules = rules, tcg_fords = fords } = tcg_env } ;
359 (bind_ids, binds', fords', rules') <- zonkTopDecls (binds `unionBags` inst_binds)
362 let { final_type_env = extendTypeEnvWithIds type_env bind_ids } ;
364 -- Compre the hi-boot iface (if any) with the real thing
365 checkHiBootIface final_type_env boot_names ;
367 -- Make the new type env available to stuff slurped from interface files
368 writeMutVar (tcg_type_env_var tcg_env) final_type_env ;
370 return (tcg_env { tcg_type_env = final_type_env,
371 tcg_binds = binds', tcg_rules = rules', tcg_fords = fords' })
374 tc_rn_src_decls :: [Name] -> [LHsDecl RdrName] -> TcM (TcGblEnv, TcLclEnv)
375 -- Loops around dealing with each top level inter-splice group
376 -- in turn, until it's dealt with the entire module
377 tc_rn_src_decls boot_names ds
378 = do { let { (first_group, group_tail) = findSplice ds } ;
379 -- If ds is [] we get ([], Nothing)
381 -- Type check the decls up to, but not including, the first splice
382 tc_envs@(tcg_env,tcl_env) <- tcRnGroup boot_names first_group ;
384 -- Bale out if errors; for example, error recovery when checking
385 -- the RHS of 'main' can mean that 'main' is not in the envt for
386 -- the subsequent checkMain test
391 -- If there is no splice, we're nearly done
393 Nothing -> do { -- Last thing: check for `main'
394 tcg_env <- checkMain ;
395 return (tcg_env, tcl_env)
398 -- If there's a splice, we must carry on
399 Just (SpliceDecl splice_expr, rest_ds) -> do {
401 failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
404 -- Rename the splice expression, and get its supporting decls
405 (rn_splice_expr, splice_fvs) <- rnLExpr splice_expr ;
406 failIfErrsM ; -- Don't typecheck if renaming failed
408 -- Execute the splice
409 spliced_decls <- tcSpliceDecls rn_splice_expr ;
411 -- Glue them on the front of the remaining decls and loop
412 setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
413 tc_rn_src_decls boot_names (spliced_decls ++ rest_ds)
418 %************************************************************************
420 Comparing the hi-boot interface with the real thing
422 %************************************************************************
424 In both one-shot mode and GHCi mode, hi-boot interfaces are demand-loaded
425 into the External Package Table. Once we've typechecked the body of the
426 module, we want to compare what we've found (gathered in a TypeEnv) with
427 the hi-boot stuff in the EPT. We do so here, using the export list of
428 the hi-boot interface as our checklist.
431 checkHiBootIface :: TypeEnv -> [Name] -> TcM ()
432 -- Compare the hi-boot file for this module (if there is one)
433 -- with the type environment we've just come up with
434 -- In the common case where there is no hi-boot file, the list
435 -- of boot_names is empty.
436 checkHiBootIface env boot_names
437 = mapM_ (check_one env) boot_names
440 check_one local_env name
443 -- Look up the hi-boot one;
444 -- it should jolly well be there (else GHC bug)
445 ; case lookupTypeEnv (eps_PTE eps) name of {
446 Nothing -> pprPanic "checkHiBootIface" (ppr name) ;
449 -- Look it up in the local type env
450 -- It should be there, but it's a programmer error if not
451 case lookupTypeEnv local_env name of
452 Nothing -> addErrTc (missingBootThing boot_thing)
453 Just real_thing -> check_thing boot_thing real_thing
457 check_thing (ATyCon boot_tc) (ATyCon real_tc)
458 | isSynTyCon boot_tc && isSynTyCon real_tc,
459 defn1 `tcEqType` substTyWith tvs2 (mkTyVarTys tvs1) defn2
462 | tyConKind boot_tc == tyConKind real_tc
465 (tvs1, defn1) = getSynTyConDefn boot_tc
466 (tvs2, defn2) = getSynTyConDefn boot_tc
468 check_thing (AnId boot_id) (AnId real_id)
469 | idType boot_id `tcEqType` idType real_id
472 check_thing (ADataCon dc1) (ADataCon dc2)
473 | idType (dataConWrapId dc1) `tcEqType` idType (dataConWrapId dc2)
476 -- Can't declare a class in a hi-boot file
478 check_thing boot_thing real_thing -- Default case; failure
479 = addErrAt (srcLocSpan (getSrcLoc real_thing))
480 (bootMisMatch real_thing)
483 missingBootThing thing
484 = ppr thing <+> ptext SLIT("is defined in the hi-boot file, but not in the module")
486 = ppr thing <+> ptext SLIT("has conflicting definitions in the module and its hi-boot file")
490 %************************************************************************
492 Type-checking the top level of a module
494 %************************************************************************
496 tcRnGroup takes a bunch of top-level source-code declarations, and
498 * gets supporting declarations from interface files
501 * and augments the TcGblEnv with the results
503 In Template Haskell it may be called repeatedly for each group of
504 declarations. It expects there to be an incoming TcGblEnv in the
505 monad; it augments it and returns the new TcGblEnv.
508 tcRnGroup :: [Name] -> HsGroup RdrName -> TcM (TcGblEnv, TcLclEnv)
509 -- Returns the variables free in the decls, for unused-binding reporting
510 tcRnGroup boot_names decls
511 = do { -- Rename the declarations
512 (tcg_env, rn_decls) <- rnTopSrcDecls decls ;
513 setGblEnv tcg_env $ do {
515 -- Typecheck the declarations
516 tcTopSrcDecls boot_names rn_decls
519 ------------------------------------------------
520 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
522 = do { -- Bring top level binders into scope
523 (rdr_env, imports) <- importsFromLocalDecls group ;
524 updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv` tcg_rdr_env gbl,
525 tcg_imports = imports `plusImportAvails` tcg_imports gbl })
528 traceRn (ptext SLIT("rnTopSrcDecls") <+> ppr rdr_env) ;
529 failIfErrsM ; -- No point in continuing if (say) we have duplicate declarations
531 -- Rename the source decls
532 (tcg_env, rn_decls) <- rnSrcDecls group ;
535 -- Dump trace of renaming part
536 rnDump (ppr rn_decls) ;
538 return (tcg_env, rn_decls)
541 ------------------------------------------------
542 tcTopSrcDecls :: [Name] -> HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
543 tcTopSrcDecls boot_names
544 (HsGroup { hs_tyclds = tycl_decls,
545 hs_instds = inst_decls,
546 hs_fords = foreign_decls,
547 hs_defds = default_decls,
548 hs_ruleds = rule_decls,
549 hs_valds = val_binds })
550 = do { -- Type-check the type and class decls, and all imported decls
551 -- The latter come in via tycl_decls
552 traceTc (text "Tc2") ;
554 tcg_env <- checkNoErrs (tcTyAndClassDecls boot_names tycl_decls) ;
555 -- tcTyAndClassDecls recovers internally, but if anything gave rise to
556 -- an error we'd better stop now, to avoid a cascade
558 -- Make these type and class decls available to stuff slurped from interface files
559 writeMutVar (tcg_type_env_var tcg_env) (tcg_type_env tcg_env) ;
562 setGblEnv tcg_env $ do {
563 -- Source-language instances, including derivings,
564 -- and import the supporting declarations
565 traceTc (text "Tc3") ;
566 (tcg_env, inst_infos, deriv_binds) <- tcInstDecls1 tycl_decls inst_decls ;
567 setGblEnv tcg_env $ do {
569 -- Foreign import declarations next. No zonking necessary
570 -- here; we can tuck them straight into the global environment.
571 traceTc (text "Tc4") ;
572 (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
573 tcExtendGlobalValEnv fi_ids $ do {
575 -- Default declarations
576 traceTc (text "Tc4a") ;
577 default_tys <- tcDefaults default_decls ;
578 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
580 -- Value declarations next
581 -- We also typecheck any extra binds that came out
582 -- of the "deriving" process (deriv_binds)
583 traceTc (text "Tc5") ;
584 (tc_val_binds, lcl_env) <- tcTopBinds (val_binds ++ deriv_binds) ;
585 setLclTypeEnv lcl_env $ do {
587 -- Second pass over class and instance declarations,
588 traceTc (text "Tc6") ;
589 (tcl_env, inst_binds) <- tcInstDecls2 tycl_decls inst_infos ;
590 showLIE (text "after instDecls2") ;
593 -- They need to be zonked, so we return them
594 traceTc (text "Tc7") ;
595 (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
598 rules <- tcRules rule_decls ;
601 traceTc (text "Tc7a") ;
602 tcg_env <- getGblEnv ;
603 let { all_binds = tc_val_binds `unionBags`
604 inst_binds `unionBags`
607 -- Extend the GblEnv with the (as yet un-zonked)
608 -- bindings, rules, foreign decls
609 tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds,
610 tcg_rules = tcg_rules tcg_env ++ rules,
611 tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls } } ;
612 return (tcg_env', lcl_env)
617 %************************************************************************
621 %************************************************************************
625 = do { ghci_mode <- getGhciMode ;
626 tcg_env <- getGblEnv ;
628 mb_main_mod <- readMutVar v_MainModIs ;
629 mb_main_fn <- readMutVar v_MainFunIs ;
630 let { main_mod = case mb_main_mod of {
631 Just mod -> mkModule mod ;
633 main_fn = case mb_main_fn of {
634 Just fn -> mkRdrUnqual (mkVarOcc (mkFastString fn)) ;
635 Nothing -> main_RDR_Unqual } } ;
637 check_main ghci_mode tcg_env main_mod main_fn
641 check_main ghci_mode tcg_env main_mod main_fn
642 -- If we are in module Main, check that 'main' is defined.
643 -- It may be imported from another module!
646 -- Blimey: a whole page of code to do this...
651 = addErrCtxt mainCtxt $
652 do { mb_main <- lookupSrcOcc_maybe main_fn
653 -- Check that 'main' is in scope
654 -- It might be imported from another module!
656 Nothing -> do { complain_no_main
659 { let { rhs = nlHsApp (nlHsVar runIOName) (nlHsVar main_name) }
660 -- :Main.main :: IO () = runIO main
662 ; (main_expr, ty) <- setSrcSpan (srcLocSpan (getSrcLoc main_name)) $
665 ; let { root_main_id = mkExportedLocalId rootMainName ty ;
666 main_bind = noLoc (VarBind root_main_id main_expr) }
668 ; return (tcg_env { tcg_binds = tcg_binds tcg_env
670 tcg_dus = tcg_dus tcg_env
671 `plusDU` usesOnly (unitFV main_name)
672 -- Record the use of 'main', so that we don't
673 -- complain about it being defined but not used
677 mod = tcg_mod tcg_env
679 complain_no_main | ghci_mode == Interactive = return ()
680 | otherwise = failWithTc noMainMsg
681 -- In interactive mode, don't worry about the absence of 'main'
682 -- In other modes, fail altogether, so that we don't go on
683 -- and complain a second time when processing the export list.
685 mainCtxt = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
686 noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn)
687 <+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
691 %*********************************************************
695 %*********************************************************
699 setInteractiveContext :: InteractiveContext -> TcRn a -> TcRn a
700 setInteractiveContext icxt thing_inside
701 = traceTc (text "setIC" <+> ppr (ic_type_env icxt)) `thenM_`
702 (updGblEnv (\env -> env {tcg_rdr_env = ic_rn_gbl_env icxt,
703 tcg_type_env = ic_type_env icxt}) $
704 updLclEnv (\env -> env {tcl_rdr = ic_rn_local_env icxt}) $
711 -> InteractiveContext
713 -> IO (Maybe (InteractiveContext, [Name], LHsExpr Id))
714 -- The returned [Name] is the same as the input except for
715 -- ExprStmt, in which case the returned [Name] is [itName]
717 -- The returned TypecheckedHsExpr is of type IO [ () ],
718 -- a list of the bound values, coerced to ().
720 tcRnStmt hsc_env ictxt rdr_stmt
721 = initTcPrintErrors hsc_env iNTERACTIVE $
722 setInteractiveContext ictxt $ do {
724 -- Rename; use CmdLineMode because tcRnStmt is only used interactively
725 ([rn_stmt], fvs) <- rnStmts DoExpr [rdr_stmt] ;
726 traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
729 -- The real work is done here
730 (bound_ids, tc_expr) <- tcUserStmt rn_stmt ;
732 traceTc (text "tcs 1") ;
733 let { -- Make all the bound ids "global" ids, now that
734 -- they're notionally top-level bindings. This is
735 -- important: otherwise when we come to compile an expression
736 -- using these ids later, the byte code generator will consider
737 -- the occurrences to be free rather than global.
738 global_ids = map (globaliseId VanillaGlobal) bound_ids ;
740 -- Update the interactive context
741 rn_env = ic_rn_local_env ictxt ;
742 type_env = ic_type_env ictxt ;
744 bound_names = map idName global_ids ;
745 new_rn_env = extendLocalRdrEnv rn_env bound_names ;
747 -- Remove any shadowed bindings from the type_env;
748 -- they are inaccessible but might, I suppose, cause
749 -- a space leak if we leave them there
750 shadowed = [ n | name <- bound_names,
751 let rdr_name = mkRdrUnqual (nameOccName name),
752 Just n <- [lookupLocalRdrEnv rn_env rdr_name] ] ;
754 filtered_type_env = delListFromNameEnv type_env shadowed ;
755 new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;
757 new_ic = ictxt { ic_rn_local_env = new_rn_env,
758 ic_type_env = new_type_env }
761 dumpOptTcRn Opt_D_dump_tc
762 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
763 text "Typechecked expr" <+> ppr tc_expr]) ;
765 returnM (new_ic, bound_names, tc_expr)
770 Here is the grand plan, implemented in tcUserStmt
772 What you type The IO [HValue] that hscStmt returns
773 ------------- ------------------------------------
774 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
777 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
780 expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
781 [NB: result not printed] bindings: [it]
783 expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
784 result showable) bindings: [it]
786 expr (of non-IO type,
787 result not showable) ==> error
791 ---------------------------
792 tcUserStmt :: LStmt Name -> TcM ([Id], LHsExpr Id)
793 tcUserStmt (L _ (ExprStmt expr _))
794 = newUnique `thenM` \ uniq ->
796 fresh_it = itName uniq
797 the_bind = noLoc $ FunBind (noLoc fresh_it) False
798 (mkMatchGroup [mkSimpleMatch [] expr])
800 tryTcLIE_ (do { -- Try this if the other fails
801 traceTc (text "tcs 1b") ;
803 nlLetStmt [HsBindGroup (unitBag the_bind) [] NonRecursive],
804 nlExprStmt (nlHsApp (nlHsVar printName)
807 (do { -- Try this first
808 traceTc (text "tcs 1a") ;
809 tc_stmts [nlBindStmt (nlVarPat fresh_it) expr] })
811 tcUserStmt stmt = tc_stmts [stmt]
813 ---------------------------
815 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
817 ret_ty = mkListTy unitTy ;
818 io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
820 names = map unLoc (collectStmtsBinders stmts) ;
822 stmt_ctxt = SC { sc_what = DoExpr,
824 sc_body = check_body,
827 infer_rhs rhs = do { (rhs', rhs_ty) <- tcInferRho rhs
828 ; [pat_ty] <- unifyTyConApp ioTyCon rhs_ty
829 ; return (rhs', pat_ty) } ;
830 check_body body = tcCheckRho body io_ret_ty ;
832 -- mk_return builds the expression
833 -- returnIO @ [()] [coerce () x, .., coerce () z]
835 -- Despite the inconvenience of building the type applications etc,
836 -- this *has* to be done in type-annotated post-typecheck form
837 -- because we are going to return a list of *polymorphic* values
838 -- coerced to type (). If we built a *source* stmt
839 -- return [coerce x, ..., coerce z]
840 -- then the type checker would instantiate x..z, and we wouldn't
841 -- get their *polymorphic* values. (And we'd get ambiguity errs
842 -- if they were overloaded, since they aren't applied to anything.)
843 mk_return ret_id ids = nlHsApp (noLoc $ TyApp (nlHsVar ret_id) [ret_ty])
844 (noLoc $ ExplicitList unitTy (map mk_item ids)) ;
845 mk_item id = nlHsApp (noLoc $ TyApp (nlHsVar unsafeCoerceId) [idType id, unitTy])
848 io_ty = mkTyConApp ioTyCon []
851 -- OK, we're ready to typecheck the stmts
852 traceTc (text "tcs 2") ;
853 ((ids, tc_expr), lie) <- getLIE $ do {
854 (ids, tc_stmts) <- tcStmtsAndThen combine stmt_ctxt stmts $
856 -- Look up the names right in the middle,
857 -- where they will all be in scope
858 ids <- mappM tcLookupId names ;
859 ret_id <- tcLookupId returnIOName ; -- return @ IO
860 return (ids, [nlResultStmt (mk_return ret_id ids)]) } ;
862 io_ids <- mappM (tcStdSyntaxName DoOrigin io_ty) monadNames ;
863 return (ids, noLoc (HsDo DoExpr tc_stmts io_ids io_ret_ty))
866 -- Simplify the context right here, so that we fail
867 -- if there aren't enough instances. Notably, when we see
869 -- we use recoverTc_ to try it <- e
870 -- and then let it = e
871 -- It's the simplify step that rejects the first.
872 traceTc (text "tcs 3") ;
873 const_binds <- tcSimplifyInteractive lie ;
875 -- Build result expression and zonk it
876 let { expr = mkHsLet const_binds tc_expr } ;
877 zonked_expr <- zonkTopLExpr expr ;
878 zonked_ids <- zonkTopBndrs ids ;
880 -- None of the Ids should be of unboxed type, because we
881 -- cast them all to HValues in the end!
882 mappM bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
884 return (zonked_ids, zonked_expr)
887 combine stmt (ids, stmts) = (ids, stmt:stmts)
888 bad_unboxed id = addErr (sep [ptext SLIT("GHCi can't bind a variable of unlifted type:"),
889 nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
893 tcRnExpr just finds the type of an expression
897 -> InteractiveContext
900 tcRnExpr hsc_env ictxt rdr_expr
901 = initTcPrintErrors hsc_env iNTERACTIVE $
902 setInteractiveContext ictxt $ do {
904 (rn_expr, fvs) <- rnLExpr rdr_expr ;
907 -- Now typecheck the expression;
908 -- it might have a rank-2 type (e.g. :t runST)
909 ((tc_expr, res_ty), lie) <- getLIE (tcInferRho rn_expr) ;
910 ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie) ;
911 tcSimplifyInteractive lie_top ;
912 qtvs' <- mappM zonkQuantifiedTyVar qtvs ;
914 let { all_expr_ty = mkForAllTys qtvs' $
915 mkFunTys (map idType dict_ids) $
917 zonkTcType all_expr_ty
920 smpl_doc = ptext SLIT("main expression")
923 tcRnType just finds the kind of a type
927 -> InteractiveContext
930 tcRnType hsc_env ictxt rdr_type
931 = initTcPrintErrors hsc_env iNTERACTIVE $
932 setInteractiveContext ictxt $ do {
934 rn_type <- rnLHsType doc rdr_type ;
937 -- Now kind-check the type
938 (ty', kind) <- kcHsType rn_type ;
942 doc = ptext SLIT("In GHCi input")
948 %************************************************************************
950 More GHCi stuff, to do with browsing and getting info
952 %************************************************************************
956 mkExportEnv :: HscEnv -> [Module] -- Expose these modules' exports only
958 mkExportEnv hsc_env exports
959 = do { mb_envs <- initTcPrintErrors hsc_env iNTERACTIVE $
960 mappM getModuleExports exports
962 Just envs -> return (foldr plusGlobalRdrEnv emptyGlobalRdrEnv envs)
963 Nothing -> return emptyGlobalRdrEnv
964 -- Some error; initTc will have printed it
967 getModuleExports :: Module -> TcM GlobalRdrEnv
969 = do { iface <- load_iface mod
970 ; loadOrphanModules (dep_orphs (mi_deps iface))
971 -- Load any orphan-module interfaces,
972 -- so their instances are visible
973 ; avails <- exportsToAvails (mi_exports iface)
974 ; let { gres = [ GRE { gre_name = name, gre_prov = vanillaProv mod }
975 | avail <- nameSetToList avails ] }
976 ; returnM (mkGlobalRdrEnv gres) }
978 vanillaProv :: Module -> Provenance
979 -- We're building a GlobalRdrEnv as if the user imported
980 -- all the specified modules into the global interactive module
981 vanillaProv mod = Imported [ImportSpec mod mod False
982 (srcLocSpan interactiveSrcLoc)] False
988 -> InteractiveContext
989 -> Module -- Module to inspect
990 -> Bool -- Grab just the exports, or the whole toplev
991 -> IO (Maybe [IfaceDecl])
993 getModuleContents hsc_env ictxt mod exports_only
994 = initTcPrintErrors hsc_env iNTERACTIVE (get_mod_contents exports_only)
996 get_mod_contents exports_only
997 | not exports_only -- We want the whole top-level type env
998 -- so it had better be a home module
1000 ; case lookupModuleEnv hpt mod of
1001 Just mod_info -> return (map toIfaceDecl $
1004 md_types (hm_details mod_info))
1005 Nothing -> ghcError (ProgramError (showSDoc (noRdrEnvErr mod)))
1006 -- This is a system error; the module should be in the HPT
1009 | otherwise -- Want the exports only
1010 = do { iface <- load_iface mod
1011 ; mappM get_decl [ (mod,avail) | (mod, avails) <- mi_exports iface
1015 get_decl (mod, avail)
1016 = do { main_name <- lookupOrig mod (availName avail)
1017 ; thing <- tcLookupGlobal main_name
1018 ; return (filter_decl (availNames avail) (toIfaceDecl thing)) }
1020 ---------------------
1021 filter_decl occs decl@(IfaceClass {ifSigs = sigs})
1022 = decl { ifSigs = filter (keep_sig occs) sigs }
1023 filter_decl occs decl@(IfaceData {ifCons = IfDataTyCon th cons})
1024 = decl { ifCons = IfDataTyCon th (filter (keep_con occs) cons) }
1025 filter_decl occs decl@(IfaceData {ifCons = IfNewTyCon con})
1026 | keep_con occs con = decl
1027 | otherwise = decl {ifCons = IfAbstractTyCon} -- Hmm?
1028 filter_decl occs decl
1031 keep_sig occs (IfaceClassOp occ _ _) = occ `elem` occs
1032 keep_con occs con = ifConOcc con `elem` occs
1034 wantToSee (AnId id) = not (isImplicitId id)
1035 wantToSee (ADataCon _) = False -- They'll come via their TyCon
1038 ---------------------
1039 load_iface mod = loadSrcInterface doc mod False {- Not boot iface -}
1041 doc = ptext SLIT("context for compiling statements")
1043 ---------------------
1044 noRdrEnvErr mod = ptext SLIT("No top-level environment available for module")
1045 <+> quotes (ppr mod)
1049 tcRnGetInfo :: HscEnv
1050 -> InteractiveContext
1052 -> IO (Maybe [(IfaceDecl,
1054 [(IfaceInst, SrcLoc)])])
1055 -- Used to implemnent :info in GHCi
1057 -- Look up a RdrName and return all the TyThings it might be
1058 -- A capitalised RdrName is given to us in the DataName namespace,
1059 -- but we want to treat it as *both* a data constructor
1060 -- *and* as a type or class constructor;
1061 -- hence the call to dataTcOccs, and we return up to two results
1062 tcRnGetInfo hsc_env ictxt rdr_name
1063 = initTcPrintErrors hsc_env iNTERACTIVE $
1064 setInteractiveContext ictxt $ do {
1066 -- If the identifier is a constructor (begins with an
1067 -- upper-case letter), then we need to consider both
1068 -- constructor and type class identifiers.
1069 let { rdr_names = dataTcOccs rdr_name } ;
1071 -- results :: [(Messages, Maybe Name)]
1072 results <- mapM (tryTc . lookupOccRn) rdr_names ;
1074 traceRn (text "xx" <+> vcat [ppr rdr_names, ppr (map snd results)]);
1075 -- The successful lookups will be (Just name)
1076 let { (warns_s, good_names) = unzip [ (msgs, name)
1077 | (msgs, Just name) <- results] ;
1078 errs_s = [msgs | (msgs, Nothing) <- results] } ;
1080 -- Fail if nothing good happened, else add warnings
1081 if null good_names then
1082 -- No lookup succeeded, so
1083 -- pick the first error message and report it
1084 -- ToDo: If one of the errors is "could be Foo.X or Baz.X",
1085 -- while the other is "X is not in scope",
1086 -- we definitely want the former; but we might pick the latter
1087 do { addMessages (head errs_s) ; failM }
1088 else -- Add deprecation warnings
1089 mapM_ addMessages warns_s ;
1091 -- And lookup up the entities, avoiding duplicates, which arise
1092 -- because constructors and record selectors are represented by
1093 -- their parent declaration
1094 let { do_one name = do { thing <- tcLookupGlobal name
1095 ; let decl = toIfaceDecl thing
1096 ; fixity <- lookupFixityRn name
1097 ; insts <- lookupInsts thing
1098 ; return (decl, fixity, getSrcLoc thing,
1099 map mk_inst insts) } ;
1100 -- For the SrcLoc, the 'thing' has better info than
1101 -- the 'name' because getting the former forced the
1102 -- declaration to be loaded into the cache
1103 mk_inst dfun = (dfunToIfaceInst dfun, getSrcLoc dfun) ;
1104 cmp (d1,_,_,_) (d2,_,_,_) = ifName d1 `compare` ifName d2 } ;
1105 results <- mapM do_one good_names ;
1106 return (fst (removeDups cmp results))
1109 lookupInsts :: TyThing -> TcM [DFunId]
1110 lookupInsts (AClass cls)
1111 = do { loadImportedInsts cls [] -- [] means load all instances for cls
1112 ; inst_envs <- tcGetInstEnvs
1113 ; return [df | (_,_,df) <- classInstances inst_envs cls] }
1115 lookupInsts (ATyCon tc)
1116 = do { eps <- getEps -- Load all instances for all classes that are
1117 -- in the type environment (which are all the ones
1118 -- we've seen in any interface file so far
1119 ; mapM_ (\c -> loadImportedInsts c [])
1120 (typeEnvClasses (eps_PTE eps))
1121 ; (pkg_ie, home_ie) <- tcGetInstEnvs -- Search all
1122 ; return (get home_ie ++ get pkg_ie) }
1124 get ie = [df | (_,_,df) <- instEnvElts ie, relevant df]
1125 relevant df = tc_name `elemNameSet` tyClsNamesOfDFunHead (idType df)
1126 tc_name = tyConName tc
1128 lookupInsts other = return []
1131 toIfaceDecl :: TyThing -> IfaceDecl
1133 = tyThingToIfaceDecl True -- Discard IdInfo
1134 emptyNameSet -- Show data cons
1135 ext_nm (munge thing)
1137 ext_nm n = ExtPkg (nameModule n) (nameOccName n)
1139 -- munge transforms a thing to it's "parent" thing
1140 munge (ADataCon dc) = ATyCon (dataConTyCon dc)
1141 munge (AnId id) = case globalIdDetails id of
1142 RecordSelId tc lbl -> ATyCon tc
1143 ClassOpId cls -> AClass cls
1145 munge other_thing = other_thing
1150 %************************************************************************
1154 %************************************************************************
1157 rnDump :: SDoc -> TcRn ()
1158 -- Dump, with a banner, if -ddump-rn
1159 rnDump doc = do { dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
1161 tcDump :: TcGblEnv -> TcRn ()
1163 = do { dflags <- getDOpts ;
1165 -- Dump short output if -ddump-types or -ddump-tc
1166 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1167 (dumpTcRn short_dump) ;
1169 -- Dump bindings if -ddump-tc
1170 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1173 short_dump = pprTcGblEnv env
1174 full_dump = pprLHsBinds (tcg_binds env)
1175 -- NB: foreign x-d's have undefined's in their types;
1176 -- hence can't show the tc_fords
1179 = do { dflags <- getDOpts ;
1180 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1181 (dumpTcRn (pprModGuts mod_guts)) ;
1183 -- Dump bindings if -ddump-tc
1184 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1186 full_dump = pprCoreBindings (mg_binds mod_guts)
1188 -- It's unpleasant having both pprModGuts and pprModDetails here
1189 pprTcGblEnv :: TcGblEnv -> SDoc
1190 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
1191 tcg_insts = dfun_ids,
1193 tcg_imports = imports })
1194 = vcat [ ppr_types dfun_ids type_env
1195 , ppr_insts dfun_ids
1196 , vcat (map ppr rules)
1197 , ppr_gen_tycons (typeEnvTyCons type_env)
1198 , ptext SLIT("Dependent modules:") <+> ppr (moduleEnvElts (imp_dep_mods imports))
1199 , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1201 pprModGuts :: ModGuts -> SDoc
1202 pprModGuts (ModGuts { mg_types = type_env,
1204 = vcat [ ppr_types [] type_env,
1208 ppr_types :: [Var] -> TypeEnv -> SDoc
1209 ppr_types dfun_ids type_env
1210 = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1212 ids = [id | id <- typeEnvIds type_env, want_sig id]
1213 want_sig id | opt_PprStyle_Debug = True
1214 | otherwise = isLocalId id &&
1215 isExternalName (idName id) &&
1216 not (id `elem` dfun_ids)
1217 -- isLocalId ignores data constructors, records selectors etc.
1218 -- The isExternalName ignores local dictionary and method bindings
1219 -- that the type checker has invented. Top-level user-defined things
1220 -- have External names.
1222 ppr_insts :: [Var] -> SDoc
1223 ppr_insts [] = empty
1224 ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)
1226 ppr_sigs :: [Var] -> SDoc
1228 -- Print type signatures; sort by OccName
1229 = vcat (map ppr_sig (sortLe le_sig ids))
1231 le_sig id1 id2 = getOccName id1 <= getOccName id2
1232 ppr_sig id = ppr id <+> dcolon <+> ppr (tidyTopType (idType id))
1234 ppr_rules :: [IdCoreRule] -> SDoc
1235 ppr_rules [] = empty
1236 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1237 nest 4 (pprIdRules rs),
1240 ppr_gen_tycons [] = empty
1241 ppr_gen_tycons tcs = vcat [ptext SLIT("Tycons with generics:"),
1242 nest 2 (fsep (map ppr (filter tyConHasGenerics tcs)))]