2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcModule]{Typechecking a whole module}
9 mkGlobalContext, getModuleContents, tcRnStmt, tcRnThing, tcRnExpr,
11 tcRnModule, checkOldIface,
12 importSupportingDecls, tcTopSrcDecls,
13 tcRnIface, tcRnExtCore
16 #include "HsVersions.h"
19 import {-# SOURCE #-} TcSplice ( tcSpliceDecls )
20 import DsMeta ( templateHaskellNames )
23 import CmdLineOpts ( DynFlag(..), opt_PprStyle_Debug, dopt )
24 import DriverState ( v_MainModIs, v_MainFunIs )
25 import HsSyn ( HsModule(..), HsBinds(..), MonoBinds(..), HsExpr(..),
26 Stmt(..), Pat(VarPat), HsStmtContext(..), RuleDecl(..),
27 HsGroup(..), SpliceDecl(..),
28 mkSimpleMatch, placeHolderType, toHsType, andMonoBinds,
29 isSrcRule, collectStmtsBinders
31 import RdrHsSyn ( RdrNameHsModule, RdrNameHsDecl, RdrNameStmt, RdrNameHsExpr,
32 emptyGroup, mkGroup, findSplice, addImpDecls, main_RDR_Unqual )
34 import PrelNames ( iNTERACTIVE, ioTyConName, printName, monadNames,
35 returnIOName, runIOName,
36 dollarMainName, itName, mAIN_Name, unsafeCoerceName
38 import RdrName ( RdrName, getRdrName, mkRdrUnqual,
39 lookupRdrEnv, elemRdrEnv )
41 import RnHsSyn ( RenamedStmt, RenamedTyClDecl,
42 ruleDeclFVs, instDeclFVs, tyClDeclFVs )
43 import TcHsSyn ( TypecheckedHsExpr, TypecheckedRuleDecl,
44 zonkTopDecls, mkHsLet,
45 zonkTopExpr, zonkTopBndrs
48 import TcExpr ( tcInferRho, tcCheckRho )
51 tyVarsOfType, tcFunResultTy, tidyTopType,
52 mkForAllTys, mkFunTys, mkTyConApp, tcSplitForAllTys
54 import Inst ( showLIE, tcStdSyntaxName )
55 import TcBinds ( tcTopBinds )
56 import TcClassDcl ( tcClassDecls2 )
57 import TcDefaults ( tcDefaults )
58 import TcEnv ( tcExtendGlobalValEnv,
59 tcExtendInstEnv, tcExtendRules,
60 tcLookupTyCon, tcLookupGlobal,
63 import TcRules ( tcRules )
64 import TcForeign ( tcForeignImports, tcForeignExports )
65 import TcIfaceSig ( tcInterfaceSigs, tcCoreBinds )
66 import TcInstDcls ( tcInstDecls1, tcIfaceInstDecls, tcInstDecls2 )
67 import TcSimplify ( tcSimplifyTop, tcSimplifyInfer )
68 import TcTyClsDecls ( tcTyAndClassDecls )
70 import RnNames ( importsFromLocalDecls, rnImports, exportsFromAvail,
72 import RnIfaces ( slurpImpDecls, checkVersions, RecompileRequired, outOfDate )
73 import RnHiFiles ( readIface, loadOldIface )
74 import RnEnv ( lookupSrcName, lookupOccRn, plusGlobalRdrEnv,
75 ubiquitousNames, implicitModuleFVs, implicitStmtFVs, dataTcOccs )
76 import RnSource ( rnSrcDecls, checkModDeprec, rnStats )
78 import CoreUnfold ( unfoldingTemplate )
79 import CoreSyn ( IdCoreRule, Bind(..) )
80 import PprCore ( pprIdRules, pprCoreBindings )
81 import ErrUtils ( mkDumpDoc, showPass, pprBagOfErrors )
82 import Id ( Id, mkLocalId, isLocalId, idName, idType, idUnfolding, setIdLocalExported )
83 import Var ( Var, setGlobalIdDetails )
84 import Module ( Module, mkHomeModule, mkModuleName, moduleName, moduleUserString, moduleEnvElts )
85 import OccName ( mkVarOcc )
86 import Name ( Name, isExternalName, getSrcLoc, nameOccName )
88 import TyCon ( tyConGenInfo )
89 import BasicTypes ( EP(..), RecFlag(..) )
90 import SrcLoc ( noSrcLoc )
92 import HscTypes ( PersistentCompilerState(..), InteractiveContext(..),
93 ModIface, ModDetails(..), ModGuts(..),
95 ModIface(..), ModDetails(..), IfaceDecls(..),
96 GhciMode(..), noDependencies,
97 Deprecations(..), plusDeprecs,
99 GenAvailInfo(Avail), availsToNameSet,
101 TypeEnv, TyThing, typeEnvTyCons,
102 extendTypeEnvWithIds, typeEnvIds, typeEnvTyCons,
103 extendLocalRdrEnv, emptyFixityEnv
106 import TcMType ( zonkTcType )
107 import TcMatches ( tcStmtsAndThen, TcStmtCtxt(..) )
108 import RdrName ( rdrEnvElts )
109 import RnExpr ( rnStmts, rnExpr )
110 import RnHiFiles ( loadInterface )
111 import RnEnv ( mkGlobalRdrEnv )
112 import TysWiredIn ( mkListTy, unitTy )
113 import IdInfo ( GlobalIdDetails(..) )
114 import NameEnv ( delListFromNameEnv )
115 import HscTypes ( GlobalRdrElt(..), GlobalRdrEnv, ImportReason(..), Provenance(..),
119 import DATA_IOREF ( readIORef )
120 import FastString ( mkFastString )
121 import Panic ( showException )
122 import List ( partition )
123 import Util ( sortLt )
128 %************************************************************************
130 Typecheck and rename a module
132 %************************************************************************
136 tcRnModule :: HscEnv -> PersistentCompilerState
138 -> IO (PersistentCompilerState, Maybe TcGblEnv)
140 tcRnModule hsc_env pcs
141 (HsModule maybe_mod exports import_decls local_decls mod_deprec loc)
142 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
144 let { this_mod = case maybe_mod of
145 Nothing -> mkHomeModule mAIN_Name -- 'module M where' is omitted
146 Just mod -> mod } ; -- The normal case
148 initTc hsc_env pcs this_mod $ addSrcLoc loc $
149 do { -- Deal with imports; sets tcg_rdr_env, tcg_imports
150 (rdr_env, imports) <- rnImports import_decls ;
151 updGblEnv ( \ gbl -> gbl { tcg_rdr_env = rdr_env,
152 tcg_imports = tcg_imports gbl `plusImportAvails` imports })
154 traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) ;
155 -- Fail if there are any errors so far
156 -- The error printing (if needed) takes advantage
157 -- of the tcg_env we have now set
160 traceRn (text "rn1a") ;
161 -- Rename and type check the declarations
162 (tcg_env, src_dus) <- tcRnSrcDecls local_decls ;
163 setGblEnv tcg_env $ do {
165 traceRn (text "rn3") ;
166 -- Check whether the entire module is deprecated
167 -- This happens only once per module
168 -- Returns the full new deprecations; a module deprecation
169 -- over-rides the earlier ones
170 let { mod_deprecs = checkModDeprec mod_deprec } ;
171 updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` mod_deprecs })
174 -- Process the export list
175 export_avails <- exportsFromAvail maybe_mod exports ;
176 updGblEnv (\gbl -> gbl { tcg_exports = export_avails })
179 -- Get any supporting decls for the exports that have not already
180 -- been sucked in for the declarations in the body of the module.
181 -- (This can happen if something is imported only to be re-exported.)
183 -- Importing these supporting declarations is required
184 -- *only* to gether usage information
185 -- (see comments with MkIface.mkImportInfo for why)
186 -- For OneShot compilation we could just throw away the decls
187 -- but for Batch or Interactive we must put them in the type
188 -- envt because they've been removed from the holding pen
189 let { export_fvs = availsToNameSet export_avails } ;
190 tcg_env <- importSupportingDecls export_fvs ;
191 setGblEnv tcg_env $ do {
193 -- Report unused names
194 let { all_dus = src_dus `plusDU` usesOnly export_fvs } ;
195 reportUnusedNames tcg_env all_dus ;
197 -- Dump output and return
204 %*********************************************************
206 \subsection{Closing up the interface decls}
208 %*********************************************************
210 Suppose we discover we don't need to recompile. Then we start from the
211 IfaceDecls in the ModIface, and fluff them up by sucking in all the decls they need.
215 -> PersistentCompilerState
216 -> ModIface -- Get the decls from here
217 -> IO (PersistentCompilerState, Maybe ModDetails)
218 -- Nothing <=> errors happened
219 tcRnIface hsc_env pcs
220 (ModIface {mi_module = mod, mi_decls = iface_decls})
221 = initTc hsc_env pcs mod $ do {
223 -- Get the supporting decls, and typecheck them all together
224 -- so that any mutually recursive types are done right
225 extra_decls <- slurpImpDecls needed ;
226 env <- typecheckIfaceDecls (group `addImpDecls` extra_decls) ;
228 returnM (ModDetails { md_types = tcg_type_env env,
229 md_insts = tcg_insts env,
230 md_rules = hsCoreRules (tcg_rules env)
231 -- All the rules from an interface are of the IfaceRuleOut form
234 rule_decls = dcl_rules iface_decls
235 inst_decls = dcl_insts iface_decls
236 tycl_decls = dcl_tycl iface_decls
237 group = emptyGroup { hs_ruleds = rule_decls,
238 hs_instds = inst_decls,
239 hs_tyclds = tycl_decls }
240 needed = unionManyNameSets (map ruleDeclFVs rule_decls) `unionNameSets`
241 unionManyNameSets (map instDeclFVs inst_decls) `unionNameSets`
242 unionManyNameSets (map tyClDeclFVs tycl_decls) `unionNameSets`
244 -- Data type decls with record selectors,
245 -- which may appear in the decls, need unpackCString
246 -- and friends. It's easier to just grab them right now.
248 hsCoreRules :: [TypecheckedRuleDecl] -> [IdCoreRule]
249 -- All post-typechecking Iface rules have the form IfaceRuleOut
250 hsCoreRules rules = [(id,rule) | IfaceRuleOut id rule <- rules]
254 %************************************************************************
256 The interactive interface
258 %************************************************************************
262 tcRnStmt :: HscEnv -> PersistentCompilerState
263 -> InteractiveContext
265 -> IO (PersistentCompilerState,
266 Maybe (InteractiveContext, [Name], TypecheckedHsExpr))
267 -- The returned [Name] is the same as the input except for
268 -- ExprStmt, in which case the returned [Name] is [itName]
270 -- The returned TypecheckedHsExpr is of type IO [ () ],
271 -- a list of the bound values, coerced to ().
273 tcRnStmt hsc_env pcs ictxt rdr_stmt
274 = initTc hsc_env pcs iNTERACTIVE $
275 setInteractiveContext ictxt $ do {
277 -- Rename; use CmdLineMode because tcRnStmt is only used interactively
278 ([rn_stmt], fvs) <- initRnInteractive ictxt
279 (rnStmts DoExpr [rdr_stmt]) ;
280 traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ;
283 -- Suck in the supporting declarations and typecheck them
284 tcg_env <- importSupportingDecls (fvs `plusFV` implicitStmtFVs fvs) ;
285 -- NB: an earlier version deleted (rdrEnvElts local_env) from
286 -- the fvs. But (a) that isn't necessary, because previously
287 -- bound things in the local_env will be in the TypeEnv, and
288 -- the renamer doesn't re-slurp such things, and
289 -- (b) it's WRONG to delete them. Consider in GHCi:
290 -- Mod> let x = e :: T
291 -- Mod> let y = x + 3
292 -- We need to pass 'x' among the fvs to slurpImpDecls, so that
293 -- the latter can see that T is a gate, and hence import the Num T
294 -- instance decl. (See the InTypEnv case in RnIfaces.slurpSourceRefs.)
295 setGblEnv tcg_env $ do {
297 -- The real work is done here
298 (bound_ids, tc_expr) <- tcUserStmt rn_stmt ;
300 traceTc (text "tcs 1") ;
301 let { -- Make all the bound ids "global" ids, now that
302 -- they're notionally top-level bindings. This is
303 -- important: otherwise when we come to compile an expression
304 -- using these ids later, the byte code generator will consider
305 -- the occurrences to be free rather than global.
306 global_ids = map globaliseId bound_ids ;
307 globaliseId id = setGlobalIdDetails id VanillaGlobal ;
309 -- Update the interactive context
310 rn_env = ic_rn_local_env ictxt ;
311 type_env = ic_type_env ictxt ;
313 bound_names = map idName global_ids ;
314 new_rn_env = extendLocalRdrEnv rn_env bound_names ;
316 -- Remove any shadowed bindings from the type_env;
317 -- they are inaccessible but might, I suppose, cause
318 -- a space leak if we leave them there
319 shadowed = [ n | name <- bound_names,
320 let rdr_name = mkRdrUnqual (nameOccName name),
321 Just n <- [lookupRdrEnv rn_env rdr_name] ] ;
323 filtered_type_env = delListFromNameEnv type_env shadowed ;
324 new_type_env = extendTypeEnvWithIds filtered_type_env global_ids ;
326 new_ic = ictxt { ic_rn_local_env = new_rn_env,
327 ic_type_env = new_type_env }
330 dumpOptTcRn Opt_D_dump_tc
331 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
332 text "Typechecked expr" <+> ppr tc_expr]) ;
334 returnM (new_ic, bound_names, tc_expr)
339 Here is the grand plan, implemented in tcUserStmt
341 What you type The IO [HValue] that hscStmt returns
342 ------------- ------------------------------------
343 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
346 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
349 expr (of IO type) ==> expr >>= \ v -> return [coerce HVal v]
350 [NB: result not printed] bindings: [it]
352 expr (of non-IO type, ==> let v = expr in print v >> return [coerce HVal v]
353 result showable) bindings: [it]
355 expr (of non-IO type,
356 result not showable) ==> error
360 ---------------------------
361 tcUserStmt :: RenamedStmt -> TcM ([Id], TypecheckedHsExpr)
362 tcUserStmt (ExprStmt expr _ loc)
363 = newUnique `thenM` \ uniq ->
365 fresh_it = itName uniq
366 the_bind = FunMonoBind fresh_it False
367 [ mkSimpleMatch [] expr placeHolderType loc ] loc
369 tryTcLIE_ (do { -- Try this if the other fails
370 traceTc (text "tcs 1b") ;
372 LetStmt (MonoBind the_bind [] NonRecursive),
373 ExprStmt (HsApp (HsVar printName) (HsVar fresh_it))
374 placeHolderType loc] })
375 (do { -- Try this first
376 traceTc (text "tcs 1a") ;
377 tc_stmts [BindStmt (VarPat fresh_it) expr loc] })
379 tcUserStmt stmt = tc_stmts [stmt]
381 ---------------------------
383 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
385 ret_ty = mkListTy unitTy ;
386 names = collectStmtsBinders stmts ;
388 stmt_ctxt = SC { sc_what = DoExpr,
390 sc_body = check_body,
393 check_rhs rhs rhs_ty = tcCheckRho rhs (mkTyConApp ioTyCon [rhs_ty]) ;
394 check_body body = tcCheckRho body (mkTyConApp ioTyCon [ret_ty]) ;
396 -- ret_expr is the expression
397 -- returnIO [coerce () x, .., coerce () z]
398 ret_stmt = ResultStmt ret_expr noSrcLoc ;
399 ret_expr = HsApp (HsVar returnIOName)
400 (ExplicitList placeHolderType (map mk_item names)) ;
401 mk_item name = HsApp (HsVar unsafeCoerceName) (HsVar name) ;
403 all_stmts = stmts ++ [ret_stmt] ;
405 io_ty = mkTyConApp ioTyCon []
408 -- OK, we're ready to typecheck the stmts
409 traceTc (text "tcs 2") ;
410 ((ids, tc_expr), lie) <- getLIE $ do {
411 (ids, tc_stmts) <- tcStmtsAndThen combine stmt_ctxt all_stmts $
413 -- Look up the names right in the middle,
414 -- where they will all be in scope
415 ids <- mappM tcLookupId names ;
417 io_ids <- mappM (tcStdSyntaxName DoOrigin io_ty) monadNames ;
418 return (ids, HsDo DoExpr tc_stmts io_ids
419 (mkTyConApp ioTyCon [ret_ty]) noSrcLoc)
422 -- Simplify the context right here, so that we fail
423 -- if there aren't enough instances. Notably, when we see
425 -- we use recoverTc_ to try it <- e
426 -- and then let it = e
427 -- It's the simplify step that rejects the first.
428 traceTc (text "tcs 3") ;
429 const_binds <- tcSimplifyTop lie ;
431 -- Build result expression and zonk it
432 let { expr = mkHsLet const_binds tc_expr } ;
433 zonked_expr <- zonkTopExpr expr ;
434 zonked_ids <- zonkTopBndrs ids ;
436 return (zonked_ids, zonked_expr)
439 combine stmt (ids, stmts) = (ids, stmt:stmts)
443 tcRnExpr just finds the type of an expression
446 tcRnExpr :: HscEnv -> PersistentCompilerState
447 -> InteractiveContext
449 -> IO (PersistentCompilerState, Maybe Type)
450 tcRnExpr hsc_env pcs ictxt rdr_expr
451 = initTc hsc_env pcs iNTERACTIVE $
452 setInteractiveContext ictxt $ do {
454 (rn_expr, fvs) <- initRnInteractive ictxt (rnExpr rdr_expr) ;
457 -- Suck in the supporting declarations and typecheck them
458 tcg_env <- importSupportingDecls (fvs `plusFV` ubiquitousNames) ;
459 setGblEnv tcg_env $ do {
461 -- Now typecheck the expression;
462 -- it might have a rank-2 type (e.g. :t runST)
463 ((tc_expr, res_ty), lie) <- getLIE (tcInferRho rn_expr) ;
464 ((qtvs, _, dict_ids), lie_top) <- getLIE (tcSimplifyInfer smpl_doc (tyVarsOfType res_ty) lie) ;
465 tcSimplifyTop lie_top ;
467 let { all_expr_ty = mkForAllTys qtvs $
468 mkFunTys (map idType dict_ids) $
470 zonkTcType all_expr_ty
473 smpl_doc = ptext SLIT("main expression")
478 tcRnThing :: HscEnv -> PersistentCompilerState
479 -> InteractiveContext
481 -> IO (PersistentCompilerState, Maybe [TyThing])
482 -- Look up a RdrName and return all the TyThings it might be
483 -- We treat a capitalised RdrName as both a data constructor
484 -- and as a type or class constructor; hence we return up to two results
485 tcRnThing hsc_env pcs ictxt rdr_name
486 = initTc hsc_env pcs iNTERACTIVE $
487 setInteractiveContext ictxt $ do {
489 -- If the identifier is a constructor (begins with an
490 -- upper-case letter), then we need to consider both
491 -- constructor and type class identifiers.
492 let { rdr_names = dataTcOccs rdr_name } ;
494 -- results :: [(Messages, Maybe Name)]
495 results <- initRnInteractive ictxt
496 (mapM (tryTc . lookupOccRn) rdr_names) ;
498 -- The successful lookups will be (Just name)
499 let { (warns_s, good_names) = unzip [ (msgs, name)
500 | (msgs, Just name) <- results] ;
501 errs_s = [msgs | (msgs, Nothing) <- results] } ;
503 -- Fail if nothing good happened, else add warnings
504 if null good_names then -- Fail
505 do { addMessages (head errs_s) ; failM }
506 else -- Add deprecation warnings
507 mapM_ addMessages warns_s ;
509 -- Slurp in the supporting declarations
510 tcg_env <- importSupportingDecls (mkFVs good_names) ;
511 setGblEnv tcg_env $ do {
513 -- And lookup up the entities
514 mapM tcLookupGlobal good_names
520 setInteractiveContext :: InteractiveContext -> TcRn m a -> TcRn m a
521 setInteractiveContext icxt thing_inside
522 = traceTc (text "setIC" <+> ppr (ic_type_env icxt)) `thenM_`
523 updGblEnv (\ env -> env { tcg_rdr_env = ic_rn_gbl_env icxt,
524 tcg_type_env = ic_type_env icxt })
527 initRnInteractive :: InteractiveContext -> RnM a -> TcM a
528 -- Set the local RdrEnv from the interactive context
529 initRnInteractive ictxt rn_thing
530 = initRn CmdLineMode $
531 setLocalRdrEnv (ic_rn_local_env ictxt) $
536 %************************************************************************
538 Type-checking external-core modules
540 %************************************************************************
543 tcRnExtCore :: HscEnv -> PersistentCompilerState
545 -> IO (PersistentCompilerState, Maybe ModGuts)
546 -- Nothing => some error occurred
548 tcRnExtCore hsc_env pcs (HsModule (Just this_mod) _ _ decls _ loc)
549 -- For external core, the module name is syntactically reqd
550 -- Rename the (Core) module. It's a bit like an interface
551 -- file: all names are original names
552 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
554 initTc hsc_env pcs this_mod $ addSrcLoc loc $ do {
556 -- Rename the source, only in interface mode.
557 -- rnSrcDecls handles fixity decls etc too, which won't occur
558 -- but that doesn't matter
559 let { local_group = mkGroup decls } ;
560 (_, rn_decls, dus) <- initRn (InterfaceMode this_mod)
561 (rnSrcDecls local_group) ;
564 -- Get the supporting decls
565 rn_imp_decls <- slurpImpDecls (duUses dus) ;
566 let { rn_decls = rn_decls `addImpDecls` rn_imp_decls } ;
568 -- Dump trace of renaming part
569 rnDump (ppr rn_decls) ;
570 rnStats rn_imp_decls ;
572 -- Typecheck them all together so that
573 -- any mutually recursive types are done right
574 tcg_env <- typecheckIfaceDecls rn_decls ;
575 setGblEnv tcg_env $ do {
577 -- Now the core bindings
578 core_prs <- tcCoreBinds (hs_coreds rn_decls) ;
579 tcExtendGlobalValEnv (map fst core_prs) $ do {
583 bndrs = map fst core_prs ;
584 my_exports = map (Avail . idName) bndrs ;
585 -- ToDo: export the data types also?
587 final_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) bndrs ;
589 mod_guts = ModGuts { mg_module = this_mod,
590 mg_usages = [], -- ToDo: compute usage
591 mg_dir_imps = [], -- ??
592 mg_deps = noDependencies, -- ??
593 mg_exports = my_exports,
594 mg_types = final_type_env,
595 mg_insts = tcg_insts tcg_env,
596 mg_rules = hsCoreRules (tcg_rules tcg_env),
597 mg_binds = [Rec core_prs],
600 mg_rdr_env = emptyGlobalRdrEnv,
601 mg_fix_env = emptyFixityEnv,
602 mg_deprecs = NoDeprecs,
606 tcCoreDump mod_guts ;
613 %************************************************************************
615 Type-checking the top level of a module
617 %************************************************************************
620 tcRnSrcDecls :: [RdrNameHsDecl] -> TcM (TcGblEnv, DefUses)
621 -- Returns the variables free in the decls
622 -- Reason: solely to report unused imports and bindings
624 = do { -- Do all the declarations
625 ((tc_envs, dus), lie) <- getLIE (tc_rn_src_decls decls) ;
627 -- tcSimplifyTop deals with constant or ambiguous InstIds.
628 -- How could there be ambiguous ones? They can only arise if a
629 -- top-level decl falls under the monomorphism
630 -- restriction, and no subsequent decl instantiates its
631 -- type. (Usually, ambiguous type variables are resolved
632 -- during the generalisation step.)
633 traceTc (text "Tc8") ;
634 setEnvs tc_envs $ do {
635 -- Setting the global env exposes the instances to tcSimplifyTop
636 -- Setting the local env exposes the local Ids, so that
637 -- we get better error messages (monomorphism restriction)
638 inst_binds <- tcSimplifyTop lie ;
640 -- Backsubstitution. This must be done last.
641 -- Even tcSimplifyTop may do some unification.
642 traceTc (text "Tc9") ;
643 let { (tcg_env, _) = tc_envs ;
644 TcGblEnv { tcg_type_env = type_env, tcg_binds = binds,
645 tcg_rules = rules, tcg_fords = fords } = tcg_env } ;
647 (bind_ids, binds', fords', rules') <- zonkTopDecls (binds `andMonoBinds` inst_binds)
650 return (tcg_env { tcg_type_env = extendTypeEnvWithIds type_env bind_ids,
651 tcg_binds = binds', tcg_rules = rules', tcg_fords = fords' },
655 tc_rn_src_decls :: [RdrNameHsDecl] -> TcM ((TcGblEnv, TcLclEnv), DefUses)
658 = do { let { (first_group, group_tail) = findSplice ds } ;
659 -- If ds is [] we get ([], Nothing)
661 -- Type check the decls up to, but not including, the first splice
662 (tc_envs@(_,tcl_env), src_dus1) <- tcRnGroup first_group ;
664 -- Bale out if errors; for example, error recovery when checking
665 -- the RHS of 'main' can mean that 'main' is not in the envt for
666 -- the subsequent checkMain test
671 -- If there is no splice, we're nearly done
673 Nothing -> do { -- Last thing: check for `main'
674 (tcg_env, main_fvs) <- checkMain ;
675 return ((tcg_env, tcl_env),
676 src_dus1 `plusDU` usesOnly main_fvs)
679 -- If there's a splice, we must carry on
680 Just (SpliceDecl splice_expr splice_loc, rest_ds) -> do {
682 failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
685 -- Rename the splice expression, and get its supporting decls
686 (rn_splice_expr, splice_fvs) <- initRn SourceMode $
687 addSrcLoc splice_loc $
689 tcg_env <- importSupportingDecls (splice_fvs `plusFV` templateHaskellNames) ;
690 setGblEnv tcg_env $ do {
692 -- Execute the splice
693 spliced_decls <- tcSpliceDecls rn_splice_expr ;
695 -- Glue them on the front of the remaining decls and loop
696 (tc_envs, src_dus2) <- tc_rn_src_decls (spliced_decls ++ rest_ds) ;
698 return (tc_envs, src_dus1 `plusDU` usesOnly splice_fvs `plusDU` src_dus2)
705 %************************************************************************
707 Type-checking the top level of a module
709 %************************************************************************
711 tcRnGroup takes a bunch of top-level source-code declarations, and
713 * gets supporting declarations from interface files
716 * and augments the TcGblEnv with the results
718 In Template Haskell it may be called repeatedly for each group of
719 declarations. It expects there to be an incoming TcGblEnv in the
720 monad; it augments it and returns the new TcGblEnv.
723 tcRnGroup :: HsGroup RdrName -> TcM ((TcGblEnv, TcLclEnv), DefUses)
724 -- Returns the variables free in the decls, for unused-binding reporting
726 = do { -- Rename the declarations
727 (tcg_env, rn_decls, src_dus) <- rnTopSrcDecls decls ;
728 setGblEnv tcg_env $ do {
730 -- Typecheck the declarations
731 tc_envs <- tcTopSrcDecls rn_decls ;
733 return (tc_envs, src_dus)
736 ------------------------------------------------
737 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name, DefUses)
739 = do { -- Bring top level binders into scope
740 (rdr_env, imports) <- importsFromLocalDecls group ;
741 updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv`
743 tcg_imports = imports `plusImportAvails`
747 failIfErrsM ; -- No point in continuing if (say) we have duplicate declarations
749 -- Rename the source decls
750 (tcg_env, rn_src_decls, src_dus) <- initRn SourceMode (rnSrcDecls group) ;
751 setGblEnv tcg_env $ do {
755 -- Import consquential imports
756 let { src_fvs = duUses src_dus } ;
757 rn_imp_decls <- slurpImpDecls (src_fvs `plusFV` implicitModuleFVs src_fvs) ;
758 let { rn_decls = rn_src_decls `addImpDecls` rn_imp_decls } ;
760 -- Dump trace of renaming part
761 rnDump (ppr rn_decls) ;
762 rnStats rn_imp_decls ;
764 return (tcg_env, rn_decls, src_dus)
767 ------------------------------------------------
768 tcTopSrcDecls :: HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
770 (HsGroup { hs_tyclds = tycl_decls,
771 hs_instds = inst_decls,
772 hs_fords = foreign_decls,
773 hs_defds = default_decls,
774 hs_ruleds = rule_decls,
775 hs_valds = val_binds })
776 = do { -- Type-check the type and class decls, and all imported decls
777 -- The latter come in via tycl_decls
778 traceTc (text "Tc2") ;
779 tcg_env <- tcTyClDecls tycl_decls ;
780 setGblEnv tcg_env $ do {
782 -- Source-language instances, including derivings,
783 -- and import the supporting declarations
784 traceTc (text "Tc3") ;
785 (tcg_env, inst_infos, deriv_binds, fvs) <- tcInstDecls1 tycl_decls inst_decls ;
786 setGblEnv tcg_env $ do {
787 tcg_env <- importSupportingDecls fvs ;
788 setGblEnv tcg_env $ do {
790 -- Foreign import declarations next. No zonking necessary
791 -- here; we can tuck them straight into the global environment.
792 traceTc (text "Tc4") ;
793 (fi_ids, fi_decls) <- tcForeignImports foreign_decls ;
794 tcExtendGlobalValEnv fi_ids $
795 updGblEnv (\gbl -> gbl { tcg_fords = tcg_fords gbl ++ fi_decls })
798 -- Default declarations
799 traceTc (text "Tc4a") ;
800 default_tys <- tcDefaults default_decls ;
801 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
803 -- Value declarations next
804 -- We also typecheck any extra binds that came out
805 -- of the "deriving" process
806 traceTc (text "Tc5") ;
807 (tc_val_binds, lcl_env) <- tcTopBinds (val_binds `ThenBinds` deriv_binds) ;
808 setLclTypeEnv lcl_env $ do {
810 -- Second pass over class and instance declarations,
811 -- plus rules and foreign exports, to generate bindings
812 traceTc (text "Tc6") ;
813 (cls_dm_binds, dm_ids) <- tcClassDecls2 tycl_decls ;
814 tcExtendGlobalValEnv dm_ids $ do {
815 inst_binds <- tcInstDecls2 inst_infos ;
816 showLIE (text "after instDecls2") ;
819 -- They need to be zonked, so we return them
820 traceTc (text "Tc7") ;
821 (foe_binds, foe_decls) <- tcForeignExports foreign_decls ;
824 -- Need to partition them because the source rules
825 -- must be zonked before adding them to tcg_rules
826 -- NB: built-in rules come in as IfaceRuleOut's, and
827 -- get added to tcg_rules right here by tcExtendRules
828 rules <- tcRules rule_decls ;
829 let { (src_rules, iface_rules) = partition isSrcRule rules } ;
830 tcExtendRules iface_rules $ do {
833 tcg_env <- getGblEnv ;
834 let { all_binds = tc_val_binds `AndMonoBinds`
835 inst_binds `AndMonoBinds`
836 cls_dm_binds `AndMonoBinds`
839 -- Extend the GblEnv with the (as yet un-zonked)
840 -- bindings, rules, foreign decls
841 tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `andMonoBinds` all_binds,
842 tcg_rules = tcg_rules tcg_env ++ src_rules,
843 tcg_fords = tcg_fords tcg_env ++ foe_decls } } ;
845 return (tcg_env', lcl_env)
850 tcTyClDecls :: [RenamedTyClDecl]
853 -- tcTyClDecls deals with
854 -- type and class decls (some source, some imported)
855 -- interface signatures (checked lazily)
857 -- It returns the TcGblEnv for this module, and side-effects the
858 -- persistent compiler state to reflect the things imported from
861 tcTyClDecls tycl_decls
863 -- tcTyAndClassDecls recovers internally, but if anything gave rise to
864 -- an error we'd better stop now, to avoid a cascade
866 traceTc (text "TyCl1") `thenM_`
867 tcTyAndClassDecls tycl_decls `thenM` \ tcg_env ->
868 -- Returns the extended environment
871 traceTc (text "TyCl2") `thenM_`
872 tcInterfaceSigs tycl_decls `thenM` \ tcg_env ->
873 -- Returns the extended environment
880 %************************************************************************
882 Load the old interface file for this module (unless
883 we have it aleady), and check whether it is up to date
886 %************************************************************************
889 checkOldIface :: HscEnv
890 -> PersistentCompilerState
892 -> FilePath -- Where the interface file is
893 -> Bool -- Source unchanged
894 -> Maybe ModIface -- Old interface from compilation manager, if any
895 -> IO (PersistentCompilerState, Maybe (RecompileRequired, Maybe ModIface))
896 -- Nothing <=> errors happened
898 checkOldIface hsc_env pcs mod iface_path source_unchanged maybe_iface
899 = do { showPass (hsc_dflags hsc_env)
900 ("Checking old interface for " ++ moduleUserString mod) ;
902 initTc hsc_env pcs mod
903 (check_old_iface iface_path source_unchanged maybe_iface)
906 check_old_iface iface_path source_unchanged maybe_iface
907 = -- CHECK WHETHER THE SOURCE HAS CHANGED
908 ifM (not source_unchanged)
909 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
912 -- If the source has changed and we're in interactive mode, avoid reading
913 -- an interface; just return the one we might have been supplied with.
914 getGhciMode `thenM` \ ghci_mode ->
915 if (ghci_mode == Interactive) && not source_unchanged then
916 returnM (outOfDate, maybe_iface)
919 case maybe_iface of {
920 Just old_iface -> -- Use the one we already have
921 checkVersions source_unchanged old_iface `thenM` \ recomp ->
922 returnM (recomp, Just old_iface)
926 -- Try and read the old interface for the current module
927 -- from the .hi file left from the last time we compiled it
928 getModule `thenM` \ this_mod ->
929 readIface this_mod iface_path False `thenM` \ read_result ->
930 case read_result of {
931 Left err -> -- Old interface file not found, or garbled; give up
932 traceHiDiffs (text "FYI: cannot read old interface file:"
933 $$ nest 4 (text (showException err))) `thenM_`
934 returnM (outOfDate, Nothing)
936 ; Right parsed_iface ->
938 -- We found the file and parsed it; now load it
939 tryTc (initRn (InterfaceMode this_mod)
940 (loadOldIface parsed_iface)) `thenM` \ ((_,errs), mb_iface) ->
942 Nothing -> -- Something went wrong in loading. The main likely thing
943 -- is that the usages mentioned B.f, where B.hi and B.hs no
944 -- longer exist. Then newGlobalName2 fails with an error message
945 -- This isn't an error; we just don't have an old iface file to
946 -- look at. Spit out a traceHiDiffs for info though.
947 traceHiDiffs (text "FYI: loading old interface file failed"
948 $$ nest 4 (docToSDoc (pprBagOfErrors errs))) `thenM_`
949 return (outOfDate, Nothing)
953 -- At last, we have got the old iface; check its versions
954 checkVersions source_unchanged iface `thenM` \ recomp ->
955 returnM (recomp, Just iface)
960 %************************************************************************
962 Type-check and rename supporting declarations
963 This is used to deal with the free vars of a splice,
964 or derived code: slurp in the necessary declarations,
965 typecheck them, and add them to the EPS
967 %************************************************************************
970 importSupportingDecls :: FreeVars -> TcM TcGblEnv
971 -- Completely deal with the supporting imports needed
972 -- by the specified free-var set
973 importSupportingDecls fvs
974 = do { traceRn (text "Import supporting decls for" <+> ppr (nameSetToList fvs)) ;
975 decls <- slurpImpDecls fvs ;
976 traceRn (text "...namely:" <+> vcat (map ppr decls)) ;
977 typecheckIfaceDecls (mkGroup decls) }
979 typecheckIfaceDecls :: HsGroup Name -> TcM TcGblEnv
980 -- The decls are all interface-file declarations
981 -- Usually they are all from other modules, but when we are reading
982 -- this module's interface from a file, it's possible that some of
983 -- them are for the module being compiled.
984 -- That is why the tcExtendX functions need to do partitioning.
986 -- If all the decls are from other modules, the returned TcGblEnv
987 -- will have an empty tc_genv, but its tc_inst_env
988 -- cache may have been augmented.
989 typecheckIfaceDecls (HsGroup { hs_tyclds = tycl_decls,
990 hs_instds = inst_decls,
991 hs_ruleds = rule_decls })
992 = do { -- Typecheck the type, class, and interface-sig decls
993 tcg_env <- tcTyClDecls tycl_decls ;
994 setGblEnv tcg_env $ do {
996 -- Typecheck the instance decls, and rules
997 -- Note that imported dictionary functions are already
998 -- in scope from the preceding tcTyClDecls
999 tcIfaceInstDecls inst_decls `thenM` \ dfuns ->
1000 tcExtendInstEnv dfuns $
1001 tcRules rule_decls `thenM` \ rules ->
1002 tcExtendRules rules $
1004 getGblEnv -- Return the environment
1010 %*********************************************************
1012 mkGlobalContext: make up an interactive context
1014 Used for initialising the lexical environment
1015 of the interactive read-eval-print loop
1017 %*********************************************************
1022 :: HscEnv -> PersistentCompilerState
1023 -> [Module] -- Expose these modules' top-level scope
1024 -> [Module] -- Expose these modules' exports only
1025 -> IO (PersistentCompilerState, Maybe GlobalRdrEnv)
1027 mkGlobalContext hsc_env pcs toplevs exports
1028 = initTc hsc_env pcs iNTERACTIVE $ do {
1030 toplev_envs <- mappM getTopLevScope toplevs ;
1031 export_envs <- mappM getModuleExports exports ;
1032 returnM (foldr plusGlobalRdrEnv emptyGlobalRdrEnv
1033 (toplev_envs ++ export_envs))
1036 getTopLevScope :: Module -> TcRn m GlobalRdrEnv
1038 = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
1039 case mi_globals iface of
1040 Nothing -> panic "getTopLevScope"
1041 Just env -> returnM env }
1043 getModuleExports :: Module -> TcRn m GlobalRdrEnv
1044 getModuleExports mod
1045 = do { iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
1046 returnM (foldl add emptyGlobalRdrEnv (mi_exports iface)) }
1048 prov_fn n = NonLocalDef ImplicitImport
1049 add env (mod,avails)
1050 = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True prov_fn avails NoDeprecs)
1052 contextDoc = text "context for compiling statements"
1058 -> PersistentCompilerState -- IN: persistent compiler state
1059 -> Module -- module to inspect
1060 -> Bool -- grab just the exports, or the whole toplev
1061 -> IO (PersistentCompilerState, Maybe [TyThing])
1063 getModuleContents hsc_env pcs mod exports_only
1064 = initTc hsc_env pcs iNTERACTIVE $ do {
1066 -- Load the interface if necessary (a home module will certainly
1067 -- alraedy be loaded, but a package module might not be)
1068 iface <- loadInterface contextDoc (moduleName mod) (ImportByUser False) ;
1070 let { export_names = availsToNameSet export_avails ;
1071 export_avails = [ avail | (mn, avails) <- mi_exports iface,
1072 avail <- avails ] } ;
1074 all_names <- if exports_only then
1076 else case mi_globals iface of {
1078 return (get_locals rdr_env) ;
1080 Nothing -> do { addErr (noRdrEnvErr mod) ;
1081 return export_names } } ;
1082 -- Invariant; we only have (not exports_only)
1083 -- for a home module so it must already be in the HIT
1084 -- So the Nothing case is a bug
1086 env <- importSupportingDecls all_names ;
1087 setGblEnv env (mappM tcLookupGlobal (nameSetToList all_names))
1090 -- Grab all the things from the global env that are locally def'd
1091 get_locals rdr_env = mkNameSet [ gre_name gre
1092 | elts <- rdrEnvElts rdr_env,
1095 -- Make a set because a name is often in the envt in
1096 -- both qualified and unqualified forms
1098 noRdrEnvErr mod = ptext SLIT("No top-level environment available for module")
1099 <+> quotes (ppr mod)
1103 %************************************************************************
1107 %************************************************************************
1111 = do { ghci_mode <- getGhciMode ;
1112 tcg_env <- getGblEnv ;
1114 mb_main_mod <- readMutVar v_MainModIs ;
1115 mb_main_fn <- readMutVar v_MainFunIs ;
1116 let { main_mod = case mb_main_mod of {
1117 Just mod -> mkModuleName mod ;
1118 Nothing -> mAIN_Name } ;
1119 main_fn = case mb_main_fn of {
1120 Just fn -> mkRdrUnqual (mkVarOcc (mkFastString fn)) ;
1121 Nothing -> main_RDR_Unqual } } ;
1123 check_main ghci_mode tcg_env main_mod main_fn
1127 check_main ghci_mode tcg_env main_mod main_fn
1128 -- If we are in module Main, check that 'main' is defined.
1129 -- It may be imported from another module, in which case
1130 -- we have to drag in its.
1132 -- Also form the definition
1133 -- $main = runIO main
1134 -- so we need to slurp in runIO too.
1136 -- ToDo: We have to return the main_name separately, because it's a
1137 -- bona fide 'use', and should be recorded as such, but the others
1140 -- Blimey: a whole page of code to do this...
1142 | mod_name /= main_mod
1143 = return (tcg_env, emptyFVs)
1145 -- Check that 'main' is in scope
1146 -- It might be imported from another module!
1148 -- We use a guard for this (rather than letting lookupSrcName fail)
1149 -- because it's not an error in ghci)
1150 | not (main_fn `elemRdrEnv` rdr_env)
1151 = do { complain_no_main; return (tcg_env, emptyFVs) }
1153 | otherwise -- OK, so the appropriate 'main' is in scope
1155 = do { main_name <- lookupSrcName main_fn ;
1157 tcg_env <- importSupportingDecls (unitFV runIOName) ;
1159 addSrcLoc (getSrcLoc main_name) $
1160 addErrCtxt mainCtxt $
1161 setGblEnv tcg_env $ do {
1163 -- $main :: IO () = runIO main
1164 let { rhs = HsApp (HsVar runIOName) (HsVar main_name) } ;
1165 (main_expr, ty) <- tcInferRho rhs ;
1167 let { dollar_main_id = setIdLocalExported (mkLocalId dollarMainName ty) ;
1168 main_bind = VarMonoBind dollar_main_id main_expr ;
1169 tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env
1170 `andMonoBinds` main_bind } } ;
1172 return (tcg_env', unitFV main_name)
1175 mod_name = moduleName (tcg_mod tcg_env)
1176 rdr_env = tcg_rdr_env tcg_env
1178 complain_no_main | ghci_mode == Interactive = return ()
1179 | otherwise = failWithTc noMainMsg
1180 -- In interactive mode, don't worry about the absence of 'main'
1181 -- In other modes, fail altogether, so that we don't go on
1182 -- and complain a second time when processing the export list.
1184 mainCtxt = ptext SLIT("When checking the type of the main function") <+> quotes (ppr main_fn)
1185 noMainMsg = ptext SLIT("The main function") <+> quotes (ppr main_fn)
1186 <+> ptext SLIT("is not defined in module") <+> quotes (ppr main_mod)
1190 %************************************************************************
1194 %************************************************************************
1197 rnDump :: SDoc -> TcRn m ()
1198 -- Dump, with a banner, if -ddump-rn
1199 rnDump doc = dumpOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc)
1201 tcDump :: TcGblEnv -> TcRn m ()
1203 = do { dflags <- getDOpts ;
1205 -- Dump short output if -ddump-types or -ddump-tc
1206 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1207 (dumpTcRn short_dump) ;
1209 -- Dump bindings if -ddump-tc
1210 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
1213 short_dump = pprTcGblEnv env
1214 full_dump = ppr (tcg_binds env)
1215 -- NB: foreign x-d's have undefined's in their types;
1216 -- hence can't show the tc_fords
1219 = do { dflags <- getDOpts ;
1220 ifM (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
1221 (dumpTcRn (pprModGuts mod_guts)) ;
1223 -- Dump bindings if -ddump-tc
1224 dumpOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) }
1226 full_dump = pprCoreBindings (mg_binds mod_guts)
1228 -- It's unpleasant having both pprModGuts and pprModDetails here
1229 pprTcGblEnv :: TcGblEnv -> SDoc
1230 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
1231 tcg_insts = dfun_ids,
1233 tcg_imports = imports })
1234 = vcat [ ppr_types dfun_ids type_env
1235 , ppr_insts dfun_ids
1236 , vcat (map ppr rules)
1237 , ppr_gen_tycons (typeEnvTyCons type_env)
1238 , ptext SLIT("Dependent modules:") <+> ppr (moduleEnvElts (imp_dep_mods imports))
1239 , ptext SLIT("Dependent packages:") <+> ppr (imp_dep_pkgs imports)]
1241 pprModGuts :: ModGuts -> SDoc
1242 pprModGuts (ModGuts { mg_types = type_env,
1244 = vcat [ ppr_types [] type_env,
1248 ppr_types :: [Var] -> TypeEnv -> SDoc
1249 ppr_types dfun_ids type_env
1250 = text "TYPE SIGNATURES" $$ nest 4 (ppr_sigs ids)
1252 ids = [id | id <- typeEnvIds type_env, want_sig id]
1253 want_sig id | opt_PprStyle_Debug = True
1254 | otherwise = isLocalId id &&
1255 isExternalName (idName id) &&
1256 not (id `elem` dfun_ids)
1257 -- isLocalId ignores data constructors, records selectors etc.
1258 -- The isExternalName ignores local dictionary and method bindings
1259 -- that the type checker has invented. Top-level user-defined things
1260 -- have External names.
1262 ppr_insts :: [Var] -> SDoc
1263 ppr_insts [] = empty
1264 ppr_insts dfun_ids = text "INSTANCES" $$ nest 4 (ppr_sigs dfun_ids)
1266 ppr_sigs :: [Var] -> SDoc
1268 -- Print type signatures
1269 -- Convert to HsType so that we get source-language style printing
1270 -- And sort by RdrName
1271 = vcat $ map ppr_sig $ sortLt lt_sig $
1272 [ (getRdrName id, toHsType (tidyTopType (idType id)))
1275 lt_sig (n1,_) (n2,_) = n1 < n2
1276 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
1279 ppr_rules :: [IdCoreRule] -> SDoc
1280 ppr_rules [] = empty
1281 ppr_rules rs = vcat [ptext SLIT("{-# RULES"),
1282 nest 4 (pprIdRules rs),
1285 ppr_gen_tycons [] = empty
1286 ppr_gen_tycons tcs = vcat [ptext SLIT("Generic type constructor details:"),
1287 nest 2 (vcat (map ppr_gen_tycon tcs))
1290 -- x&y are now Id's, not CoreExpr's
1292 | Just ep <- tyConGenInfo tycon
1293 = (ppr tycon <> colon) $$ nest 4 (ppr_ep ep)
1295 | otherwise = ppr tycon <> colon <+> ptext SLIT("Not derivable")
1298 = vcat [ ptext SLIT("Rep type:") <+> ppr (tcFunResultTy from_tau),
1299 ptext SLIT("From:") <+> ppr (unfoldingTemplate (idUnfolding from)),
1300 ptext SLIT("To:") <+> ppr (unfoldingTemplate (idUnfolding to))
1303 (_,from_tau) = tcSplitForAllTys (idType from)