2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcIfaceSig]{Type checking of type signatures in interface files}
8 tcImportDecl, typecheckIface,
9 tcIfaceKind, loadImportedInsts,
12 #include "HsVersions.h"
15 import LoadIface ( loadHomeInterface, predInstGates )
16 import IfaceEnv ( lookupIfaceTop, newGlobalBinder, lookupOrig,
17 extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
18 tcIfaceTyVar, tcIfaceTyCon, tcIfaceClass, tcIfaceExtId,
19 tcIfaceDataCon, tcIfaceLclId,
20 newIfaceName, newIfaceNames )
21 import BuildTyCl ( buildSynTyCon, buildAlgTyCon, buildDataCon, buildClass )
23 import Type ( Kind, openTypeKind, liftedTypeKind,
24 unliftedTypeKind, mkArrowKind, splitTyConApp,
25 mkTyVarTys, mkGenTyConApp, mkTyVarTys, ThetaType )
26 import TypeRep ( Type(..), PredType(..) )
27 import TyCon ( TyCon, tyConName )
28 import HscTypes ( ExternalPackageState(..), PackageInstEnv,
29 TyThing(..), implicitTyThings,
30 ModIface(..), ModDetails(..), InstPool,
31 TypeEnv, mkTypeEnv, extendTypeEnvList, lookupTypeEnv,
32 DeclPool, RulePool, Pool(..), Gated, addRuleToPool )
33 import InstEnv ( extendInstEnv )
35 import Rules ( extendRuleBaseList )
36 import CoreUtils ( exprType )
38 import CoreLint ( lintUnfolding )
39 import WorkWrap ( mkWrapper )
40 import InstEnv ( DFunId )
41 import Id ( Id, mkVanillaGlobal, mkLocalId )
42 import MkId ( mkFCallId )
43 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
44 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
45 setArityInfo, setInlinePragInfo, setCafInfo,
46 vanillaIdInfo, newStrictnessInfo )
47 import Class ( Class )
48 import TyCon ( DataConDetails(..), tyConDataCons, tyConTyVars, isTupleTyCon, mkForeignTyCon )
49 import DataCon ( dataConWorkId, dataConExistentialTyVars, dataConArgTys )
50 import TysWiredIn ( tupleCon )
51 import Var ( TyVar, mkTyVar, tyVarKind )
52 import Name ( Name, NamedThing(..), nameModuleName, nameModule, nameOccName,
53 isWiredInName, wiredInNameTyThing_maybe, nameParent )
55 import OccName ( OccName )
56 import Module ( Module, ModuleName, moduleName )
57 import UniqSupply ( initUs_ )
59 import SrcLoc ( noSrcLoc )
60 import Util ( zipWithEqual, dropList, equalLength )
61 import Maybes ( expectJust )
62 import CmdLineOpts ( DynFlag(..) )
71 An IfaceDecl is populated with RdrNames, and these are not renamed to
72 Names before typechecking, because there should be no scope errors etc.
74 -- For (b) consider: f = $(...h....)
75 -- where h is imported, and calls f via an hi-boot file.
76 -- This is bad! But it is not seen as a staging error, because h
77 -- is indeed imported. We don't want the type-checker to black-hole
78 -- when simplifying and compiling the splice!
80 -- Simple solution: discard any unfolding that mentions a variable
81 -- bound in this module (and hence not yet processed).
82 -- The discarding happens when forkM finds a type error.
84 %************************************************************************
86 %* tcImportDecl is the key function for "faulting in" *
89 %************************************************************************
91 The main idea is this. We are chugging along type-checking source code, and
92 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
93 it in the EPS type envt. So it
95 2 gets the decl for GHC.Base.map
96 3 typechecks it via tcIfaceDecl
97 4 and adds it to the type env in the EPS
99 Note that DURING STEP 4, we may find that map's type mentions a type
100 constructor that also
102 Notice that for imported things we read the current version from the EPS
103 mutable variable. This is important in situations like
105 where the code that e1 expands to might import some defns that
106 also turn out to be needed by the code that e2 expands to.
109 tcImportDecl :: Name -> IfG TyThing
110 -- Get the TyThing for this Name from an interface file
113 -- Make sure the interface is loaded
114 ; let { nd_doc = ptext SLIT("Need decl for") <+> ppr name }
116 ; loadHomeInterface nd_doc name
118 -- Get the real name of the thing, with a correct nameParent field.
119 -- Before the interface is loaded, we may have a non-commital 'Nothing' in
120 -- the namePareent field (made up by IfaceEnv.lookupOrig), but
121 -- loading the interface updates the name cache.
122 -- We need the right nameParent field in getThing
123 ; real_name <- lookupOrig (nameModuleName name) (nameOccName name)
125 -- Get the decl out of the EPS
126 ; main_thing <- ASSERT( real_name == name ) -- Unique should not change!
129 -- Record the import in the type env,
130 -- slurp any rules it allows in
131 ; recordImportOf main_thing
133 ; let { extra | getName main_thing == real_name = empty
134 | otherwise = brackets (ptext SLIT("when seeking") <+> ppr real_name) }
135 ; traceIf (ptext SLIT("...imported decl for") <+> ppr main_thing <+> extra)
138 -- Look up the wanted Name in the type envt; it might be
139 -- one of the subordinate members of the input thing
140 ; if real_name == getName main_thing
141 then return main_thing
144 ; return (expectJust "tcImportDecl" $
145 lookupTypeEnv (eps_PTE eps) real_name) }}
147 recordImportOf :: TyThing -> IfG ()
148 -- Update the EPS to record the import of the Thing
149 -- (a) augment the type environment; this is done even for wired-in
150 -- things, so that we don't go through this rigmarole a second time
151 -- (b) slurp in any rules to maintain the invariant that any rule
152 -- whose gates are all in the type envt, is in eps_rule_base
155 = do { (new_things, iface_rules) <- updateEps (\ eps ->
156 let { new_things = thing : implicitTyThings thing
157 ; new_type_env = extendTypeEnvList (eps_PTE eps) new_things
158 -- NB: opportunity for a very subtle loop here!
159 -- If working out what the implicitTyThings are involves poking
160 -- any of the fork'd thunks in 'thing', then here's what happens
161 -- * recordImportOf succeed, extending type-env with a thunk
162 -- * the next guy to pull on type-env forces the thunk
163 -- * which pokes the suspended forks
164 -- * which, to execute, need to consult type-env (to check
165 -- entirely unrelated types, perhaps)
167 ; (new_rules, iface_rules) = selectRules (eps_rules eps)
168 (map getName new_things)
170 in (eps { eps_PTE = new_type_env, eps_rules = new_rules },
171 (new_things, iface_rules))
174 -- Now type-check those rules (which may side-effect the EPS again)
175 ; traceIf (text "tcImport: extend type env" <+> ppr new_things)
176 ; core_rules <- mapM tc_rule iface_rules
177 ; updateEps_ (\ eps ->
178 eps { eps_rule_base = extendRuleBaseList (eps_rule_base eps) core_rules }
181 tc_rule (mod, rule) = initIfaceLcl mod (tcIfaceRule rule)
183 getThing :: Name -> IfG TyThing
184 -- Find and typecheck the thing; the Name might be a "subordinate name"
185 -- of the "main thing" (e.g. the constructor of a data type declaration)
186 -- The Thing we return is the parent "main thing"
189 | Just thing <- wiredInNameTyThing_maybe name
192 | otherwise = do -- The normal case, not wired in
193 { -- Get the decl from the pool
194 decl <- updateEps (\ eps ->
196 (decls', decl) = selectDecl (eps_decls eps) name
198 (eps { eps_decls = decls' }, decl))
201 -- Side-effects EPS by faulting in any needed decls
202 -- (via nested calls to tcImportDecl)
203 ; initIfaceLcl (nameModuleName name) (tcIfaceDecl decl) }
206 selectDecl :: DeclPool -> Name -> (DeclPool, IfaceDecl)
207 -- Use nameParent to get the parent name of the thing
208 selectDecl (Pool decls_map n_in n_out) name
209 = (Pool decls' n_in (n_out+1), decl)
211 main_name = nameParent name
212 decl = case lookupNameEnv decls_map main_name of
213 Nothing -> pprPanic "selectDecl" (ppr main_name <+> ppr name) ;
216 decls' = delFromNameEnv decls_map main_name
219 %************************************************************************
223 %************************************************************************
226 typecheckIface :: ModIface -> IfG ModDetails
227 -- Used when we decide not to recompile, but intead to use the
228 -- interface to construct the type environment for the module
230 = initIfaceLcl (moduleName (mi_module iface)) $
231 do { ty_things <- mapM (tcIfaceDecl . snd) (mi_decls iface)
232 ; rules <- mapM tcIfaceRule (mi_rules iface)
233 ; dfuns <- mapM tcIfaceInst (mi_insts iface)
234 ; return (ModDetails { md_types = mkTypeEnv ty_things,
236 md_rules = rules }) }
240 %************************************************************************
242 Type and class declarations
244 %************************************************************************
246 When typechecking a data type decl, we *lazily* (via forkM) typecheck
247 the constructor argument types. This is in the hope that we may never
248 poke on those argument types, and hence may never need to load the
249 interface files for types mentioned in the arg types.
252 data Foo.S = MkS Baz.T
253 Mabye we can get away without even loading the interface for Baz!
255 This is not just a performance thing. Suppose we have
256 data Foo.S = MkS Baz.T
257 data Baz.T = MkT Foo.S
258 (in different interface files, of course).
259 Now, first we load and typecheck Foo.S, and add it to the type envt.
260 If we do explore MkS's argument, we'll load and typecheck Baz.T.
261 If we explore MkT's argument we'll find Foo.S already in the envt.
263 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
264 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
265 which isn't done yet.
267 All very cunning. However, there is a rather subtle gotcha which bit
268 me when developing this stuff. When we typecheck the decl for S, we
269 extend the type envt with S, MkS, and all its implicit Ids. Suppose
270 (a bug, but it happened) that the list of implicit Ids depended in
271 turn on the constructor arg types. Then the following sequence of
273 * we build a thunk <t> for the constructor arg tys
274 * we build a thunk for the extended type environment (depends on <t>)
275 * we write the extended type envt into the global EPS mutvar
277 Now we look something up in the type envt
279 * which reads the global type envt out of the global EPS mutvar
280 * but that depends in turn on <t>
282 It's subtle, because, it'd work fine if we typechecked the constructor args
283 eagerly -- they don't need the extended type envt. They just get the extended
284 type envt by accident, because they look at it later.
286 What this means is that the implicitTyThings MUST NOT DEPEND on any of
291 tcIfaceDecl :: IfaceDecl -> IfL TyThing
293 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
294 = do { name <- lookupIfaceTop occ_name
295 ; ty <- tcIfaceType iface_type
296 ; info <- tcIdInfo name ty info
297 ; return (AnId (mkVanillaGlobal name ty info)) }
299 tcIfaceDecl (IfaceData {ifND = new_or_data, ifName = occ_name,
300 ifTyVars = tv_bndrs, ifCtxt = rdr_ctxt,
302 ifVrcs = arg_vrcs, ifRec = is_rec,
303 ifGeneric = want_generic })
304 = do { tc_name <- lookupIfaceTop occ_name
305 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
307 { traceIf (text "tcIfaceDecl" <+> ppr rdr_ctxt)
309 ; ctxt <- forkM (ptext SLIT("Ctxt of data decl") <+> ppr tc_name) $
311 -- The reason for laziness here is to postpone
312 -- looking at the context, because the class may not
313 -- be in the type envt yet. E.g.
314 -- class Real a where { toRat :: a -> Ratio Integer }
315 -- data (Real a) => Ratio a = ...
316 -- We suck in the decl for Real, and type check it, which sucks
317 -- in the data type Ratio; but we must postpone typechecking the
320 ; tycon <- fixM ( \ tycon -> do
321 { cons <- tcIfaceDataCons tycon tyvars ctxt rdr_cons
322 ; tycon <- buildAlgTyCon new_or_data tc_name tyvars ctxt cons
323 arg_vrcs is_rec want_generic
326 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
327 ; return (ATyCon tycon)
330 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
331 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
332 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
333 { tc_name <- lookupIfaceTop occ_name
334 ; rhs_ty <- tcIfaceType rdr_rhs_ty
335 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
338 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
339 ifFDs = rdr_fds, ifSigs = rdr_sigs,
340 ifVrcs = tc_vrcs, ifRec = tc_isrec })
341 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
342 { cls_name <- lookupIfaceTop occ_name
343 ; ctxt <- tcIfaceCtxt rdr_ctxt
344 ; sigs <- mappM tc_sig rdr_sigs
345 ; fds <- mappM tc_fd rdr_fds
346 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
347 ; return (AClass cls) }
349 tc_sig (IfaceClassOp occ dm rdr_ty)
350 = do { op_name <- lookupIfaceTop occ
351 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
352 -- Must be done lazily for just the same reason as the
353 -- context of a data decl: the type sig might mention the
354 -- class being defined
355 ; return (op_name, dm, op_ty) }
357 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
359 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
360 ; tvs2' <- mappM tcIfaceTyVar tvs2
361 ; return (tvs1', tvs2') }
363 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
364 = do { name <- lookupIfaceTop rdr_name
365 ; return (ATyCon (mkForeignTyCon name ext_name
366 liftedTypeKind 0 [])) }
368 tcIfaceDataCons tycon tyvars ctxt Unknown
371 tcIfaceDataCons tycon tyvars ctxt (DataCons cs)
372 = mappM tc_con_decl cs `thenM` \ data_cons ->
373 returnM (DataCons data_cons)
375 tc_con_decl (IfaceConDecl occ ex_tvs ex_ctxt args stricts field_lbls)
376 = bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
377 { name <- lookupIfaceTop occ
378 ; ex_theta <- tcIfaceCtxt ex_ctxt -- Laziness seems not worth the bother here
380 -- Read the argument types, but lazily to avoid faulting in
381 -- the component types unless they are really needed
382 ; arg_tys <- forkM (mk_doc name args) (mappM tcIfaceType args) ;
384 ; lbl_names <- mappM lookupIfaceTop field_lbls
386 ; buildDataCon name stricts lbl_names
387 tyvars ctxt ex_tyvars ex_theta
390 mk_doc con_name args = ptext SLIT("Constructor") <+> sep [ppr con_name, ppr args]
394 %************************************************************************
398 %************************************************************************
400 The gating story for instance declarations
401 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402 When we are looking for a dict (C t1..tn), we slurp in instance decls for
404 mention at least one of the type constructors
405 at the roots of t1..tn
407 Why "at least one" rather than "all"? Because functional dependencies
408 complicate the picture. Consider
409 class C a b | a->b where ...
410 instance C Foo Baz where ...
411 Here, the gates are really only C and Foo, *not* Baz.
412 That is, if C and Foo are visible, even if Baz isn't, we must
413 slurp the decl, even if Baz is thus far completely unknown to the
416 Why "roots of the types"? Reason is overlap. For example, suppose there
417 are interfaces in the pool for
421 Then, if we are trying to resolve (C Int x), we need (a)
422 if we are trying to resolve (C x [y]), we need *both* (b) and (c),
423 even though T is not involved yet, so that we spot the overlap.
426 loadImportedInsts :: Class -> [Type] -> TcM PackageInstEnv
427 loadImportedInsts cls tys
428 = do { -- Get interfaces for wired-in things, such as Integer
429 -- Any non-wired-in tycons will already be loaded, else
430 -- we couldn't have them in the Type
431 ; this_mod <- getModule
432 ; let { (cls_gate, tc_gates) = predInstGates cls tys
433 ; imp_wi n = isWiredInName n && this_mod /= nameModule n
434 ; wired_tcs = filter imp_wi tc_gates }
435 -- Wired-in tycons not from this module. The "this-module"
436 -- test bites only when compiling Base etc, because loadHomeInterface
437 -- barfs if it's asked to load a non-existent interface
438 ; if null wired_tcs then returnM ()
439 else initIfaceTcRn (mapM_ (loadHomeInterface wired_doc) wired_tcs)
441 ; eps_var <- getEpsVar
442 ; eps <- readMutVar eps_var
444 -- Suck in the instances
445 ; let { (inst_pool', iface_insts)
446 = selectInsts (eps_insts eps) cls_gate tc_gates }
448 ; traceTc (text "loadImportedInsts" <+> vcat [ppr cls <+> ppr tys,
449 text "new pool" <+> ppr inst_pool',
450 text "new insts" <+> ppr iface_insts])
452 -- Empty => finish up rapidly, without writing to eps
453 ; if null iface_insts then
454 return (eps_inst_env eps)
456 { writeMutVar eps_var (eps {eps_insts = inst_pool'})
458 -- Typecheck the new instances
459 ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
461 -- And put them in the package instance environment
462 ; updateEps ( \ eps ->
464 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
466 (eps { eps_inst_env = inst_env' }, inst_env')
469 wired_doc = ptext SLIT("Need home inteface for wired-in thing")
471 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
473 tcIfaceInst :: IfaceInst -> IfL DFunId
474 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
475 = tcIfaceExtId (LocalTop dfun_occ)
477 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
478 selectInsts pool@(Pool insts n_in n_out) cls tycons
479 = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
481 (insts', iface_insts)
482 = case lookupNameEnv insts cls of {
483 Nothing -> (insts, []) ;
486 case foldl choose ([],[]) gated_insts of {
487 (_, []) -> (insts, []) ; -- None picked
488 (gated_insts', iface_insts') ->
490 (extendNameEnv insts cls gated_insts', iface_insts') }}
492 -- Reverses the gated decls, but that doesn't matter
493 choose (gis, decls) (gates, decl)
494 | any (`elem` tycons) gates = (gis, decl:decls)
495 | otherwise = ((gates,decl) : gis, decls)
498 %************************************************************************
502 %************************************************************************
504 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
505 are in the type environment. However, remember that typechecking a Rule may
506 (as a side effect) augment the type envt, and so we may need to iterate the process.
509 selectRules :: RulePool
510 -> [Name] -- Names of things being added
511 -> TypeEnv -- New type env, including things being added
512 -> (RulePool, [(ModuleName, IfaceRule)])
513 selectRules (Pool rules n_in n_out) new_names type_env
514 = (Pool rules' n_in (n_out + length iface_rules), iface_rules)
516 (rules', iface_rules) = foldl select_one (rules, []) new_names
518 select_one :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Name
519 -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
520 select_one (rules, decls) name
521 = case lookupNameEnv rules name of
522 Nothing -> (rules, decls)
523 Just gated_rules -> foldl filter_rule (delFromNameEnv rules name, decls) gated_rules
525 filter_rule :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Gated IfaceRule
526 -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
527 filter_rule (rules, decls) (rule_fvs, rule)
528 = case [fv | fv <- rule_fvs, not (fv `elemNameEnv` type_env)] of
529 [] -> -- No remaining FVs, so slurp it
531 fvs -> -- There leftover fvs, so toss it back in the pool
532 (addRuleToPool rules rule fvs, decls)
534 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
535 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
536 ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
537 = bindIfaceBndrs bndrs $ \ bndrs' ->
538 do { fn <- tcIfaceExtId fn_rdr
539 ; args' <- mappM tcIfaceExpr args
540 ; rhs' <- tcIfaceExpr rhs
541 ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
543 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
544 = do { fn <- tcIfaceExtId fn_rdr
545 ; returnM (fn, core_rule) }
549 %************************************************************************
553 %************************************************************************
556 tcIfaceKind :: IfaceKind -> Kind
557 tcIfaceKind IfaceOpenTypeKind = openTypeKind
558 tcIfaceKind IfaceLiftedTypeKind = liftedTypeKind
559 tcIfaceKind IfaceUnliftedTypeKind = unliftedTypeKind
560 tcIfaceKind (IfaceFunKind k1 k2) = mkArrowKind (tcIfaceKind k1) (tcIfaceKind k2)
562 -----------------------------------------
563 tcIfaceType :: IfaceType -> IfL Type
564 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
565 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
566 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
567 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
568 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
569 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
571 tcIfaceTypes tys = mapM tcIfaceType tys
573 -----------------------------------------
574 tcIfacePredType :: IfacePredType -> IfL PredType
575 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
576 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
578 -----------------------------------------
579 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
580 tcIfaceCtxt sts = mappM tcIfacePredType sts
584 %************************************************************************
588 %************************************************************************
591 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
592 tcIfaceExpr (IfaceType ty)
593 = tcIfaceType ty `thenM` \ ty' ->
596 tcIfaceExpr (IfaceLcl name)
597 = tcIfaceLclId name `thenM` \ id ->
600 tcIfaceExpr (IfaceExt gbl)
601 = tcIfaceExtId gbl `thenM` \ id ->
604 tcIfaceExpr (IfaceLit lit)
607 tcIfaceExpr (IfaceFCall cc ty)
608 = tcIfaceType ty `thenM` \ ty' ->
609 newUnique `thenM` \ u ->
610 returnM (Var (mkFCallId u cc ty'))
612 tcIfaceExpr (IfaceTuple boxity args)
613 = mappM tcIfaceExpr args `thenM` \ args' ->
615 -- Put the missing type arguments back in
616 con_args = map (Type . exprType) args' ++ args'
618 returnM (mkApps (Var con_id) con_args)
621 con_id = dataConWorkId (tupleCon boxity arity)
624 tcIfaceExpr (IfaceLam bndr body)
625 = bindIfaceBndr bndr $ \ bndr' ->
626 tcIfaceExpr body `thenM` \ body' ->
627 returnM (Lam bndr' body')
629 tcIfaceExpr (IfaceApp fun arg)
630 = tcIfaceExpr fun `thenM` \ fun' ->
631 tcIfaceExpr arg `thenM` \ arg' ->
632 returnM (App fun' arg')
634 tcIfaceExpr (IfaceCase scrut case_bndr alts)
635 = tcIfaceExpr scrut `thenM` \ scrut' ->
636 newIfaceName case_bndr `thenM` \ case_bndr_name ->
638 scrut_ty = exprType scrut'
639 case_bndr' = mkLocalId case_bndr_name scrut_ty
640 tc_app = splitTyConApp scrut_ty
641 -- NB: Won't always succeed (polymoprhic case)
642 -- but won't be demanded in those cases
643 -- NB: not tcSplitTyConApp; we are looking at Core here
644 -- look through non-rec newtypes to find the tycon that
645 -- corresponds to the datacon in this case alternative
647 extendIfaceIdEnv [case_bndr'] $
648 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
649 returnM (Case scrut' case_bndr' alts')
651 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
652 = tcIfaceExpr rhs `thenM` \ rhs' ->
653 bindIfaceId bndr $ \ bndr' ->
654 tcIfaceExpr body `thenM` \ body' ->
655 returnM (Let (NonRec bndr' rhs') body')
657 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
658 = bindIfaceIds bndrs $ \ bndrs' ->
659 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
660 tcIfaceExpr body `thenM` \ body' ->
661 returnM (Let (Rec (bndrs' `zip` rhss')) body')
663 (bndrs, rhss) = unzip pairs
665 tcIfaceExpr (IfaceNote note expr)
666 = tcIfaceExpr expr `thenM` \ expr' ->
668 IfaceCoerce to_ty -> tcIfaceType to_ty `thenM` \ to_ty' ->
669 returnM (Note (Coerce to_ty'
670 (exprType expr')) expr')
671 IfaceInlineCall -> returnM (Note InlineCall expr')
672 IfaceInlineMe -> returnM (Note InlineMe expr')
673 IfaceSCC cc -> returnM (Note (SCC cc) expr')
674 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
676 -------------------------
677 tcIfaceAlt _ (IfaceDefault, names, rhs)
678 = ASSERT( null names )
679 tcIfaceExpr rhs `thenM` \ rhs' ->
680 returnM (DEFAULT, [], rhs')
682 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
683 = ASSERT( null names )
684 tcIfaceExpr rhs `thenM` \ rhs' ->
685 returnM (LitAlt lit, [], rhs')
687 -- A case alternative is made quite a bit more complicated
688 -- by the fact that we omit type annotations because we can
689 -- work them out. True enough, but its not that easy!
690 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
692 tycon_mod = nameModuleName (tyConName tycon)
694 tcIfaceDataCon (ExtPkg tycon_mod data_occ) `thenM` \ con ->
695 newIfaceNames arg_occs `thenM` \ arg_names ->
697 ex_tyvars = dataConExistentialTyVars con
698 main_tyvars = tyConTyVars tycon
699 ex_tyvars' = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars]
700 ex_tys' = mkTyVarTys ex_tyvars'
701 arg_tys = dataConArgTys con (inst_tys ++ ex_tys')
702 id_names = dropList ex_tyvars arg_names
705 | not (equalLength id_names arg_tys)
706 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
707 (ppr main_tyvars <+> ppr ex_tyvars) $$
711 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
713 ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
714 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$ ppr main_tyvars )
715 extendIfaceTyVarEnv ex_tyvars' $
716 extendIfaceIdEnv arg_ids $
717 tcIfaceExpr rhs `thenM` \ rhs' ->
718 returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
720 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
721 = newIfaceNames arg_occs `thenM` \ arg_names ->
723 [con] = tyConDataCons tycon
724 arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
726 ASSERT( isTupleTyCon tycon )
727 extendIfaceIdEnv arg_ids $
728 tcIfaceExpr rhs `thenM` \ rhs' ->
729 returnM (DataAlt con, arg_ids, rhs')
734 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
735 tcExtCoreBindings mod [] = return []
736 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
738 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
739 do_one mod (IfaceNonRec bndr rhs) thing_inside
740 = do { rhs' <- tcIfaceExpr rhs
741 ; bndr' <- newExtCoreBndr mod bndr
742 ; extendIfaceIdEnv [bndr'] $ do
743 { core_binds <- thing_inside
744 ; return (NonRec bndr' rhs' : core_binds) }}
746 do_one mod (IfaceRec pairs) thing_inside
747 = do { bndrs' <- mappM (newExtCoreBndr mod) bndrs
748 ; extendIfaceIdEnv bndrs' $ do
749 { rhss' <- mappM tcIfaceExpr rhss
750 ; core_binds <- thing_inside
751 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
753 (bndrs,rhss) = unzip pairs
757 %************************************************************************
761 %************************************************************************
764 tcIdInfo name ty NoInfo = return vanillaIdInfo
765 tcIdInfo name ty DiscardedInfo = return vanillaIdInfo
766 tcIdInfo name ty (HasInfo iface_info)
767 = foldlM tcPrag init_info iface_info
769 -- Set the CgInfo to something sensible but uninformative before
770 -- we start; default assumption is that it has CAFs
771 init_info = vanillaIdInfo
773 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
774 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
775 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
777 -- The next two are lazy, so they don't transitively suck stuff in
778 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
779 tcPrag info (HsUnfold inline_prag expr)
780 = tcPragExpr name expr `thenM` \ maybe_expr' ->
782 -- maybe_expr' doesn't get looked at if the unfolding
783 -- is never inspected; so the typecheck doesn't even happen
784 unfold_info = case maybe_expr' of
785 Nothing -> noUnfolding
786 Just expr' -> mkTopUnfolding expr'
788 returnM (info `setUnfoldingInfoLazily` unfold_info
789 `setInlinePragInfo` inline_prag)
793 tcWorkerInfo ty info wkr_name arity
794 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
796 -- We return without testing maybe_wkr_id, but as soon as info is
797 -- looked at we will test it. That's ok, because its outside the
798 -- knot; and there seems no big reason to further defer the
799 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
800 -- over the unfolding until it's actually used does seem worth while.)
801 ; us <- newUniqueSupply
803 ; returnM (case mb_wkr_id of
805 Just wkr_id -> add_wkr_info us wkr_id info) }
807 doc = text "Worker for" <+> ppr wkr_name
808 add_wkr_info us wkr_id info
809 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
810 `setWorkerInfo` HasWorker wkr_id arity
812 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
814 -- We are relying here on strictness info always appearing
815 -- before worker info, fingers crossed ....
816 strict_sig = case newStrictnessInfo info of
818 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
821 For unfoldings we try to do the job lazily, so that we never type check
822 an unfolding that isn't going to be looked at.
825 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
828 tcIfaceExpr expr `thenM` \ core_expr' ->
830 -- Check for type consistency in the unfolding
831 ifOptM Opt_DoCoreLinting (
832 case lintUnfolding noSrcLoc [{- in scope -}] core_expr' of
833 Nothing -> returnM ()
834 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
839 doc = text "Unfolding of" <+> ppr name
844 %************************************************************************
848 %************************************************************************
851 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
852 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
853 = bindIfaceId bndr thing_inside
854 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
855 = bindIfaceTyVar bndr thing_inside
857 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
858 bindIfaceBndrs [] thing_inside = thing_inside []
859 bindIfaceBndrs (b:bs) thing_inside
860 = bindIfaceBndr b $ \ b' ->
861 bindIfaceBndrs bs $ \ bs' ->
862 thing_inside (b':bs')
864 -----------------------
865 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
866 bindIfaceId (occ, ty) thing_inside
867 = do { name <- newIfaceName occ
868 ; ty' <- tcIfaceType ty
869 ; let { id = mkLocalId name ty' }
870 ; extendIfaceIdEnv [id] (thing_inside id) }
872 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
873 bindIfaceIds bndrs thing_inside
874 = do { names <- newIfaceNames occs
875 ; tys' <- mappM tcIfaceType tys
876 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
877 ; extendIfaceIdEnv ids (thing_inside ids) }
879 (occs,tys) = unzip bndrs
882 -----------------------
883 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
884 newExtCoreBndr mod (occ, ty)
885 = do { name <- newGlobalBinder mod occ Nothing noSrcLoc
886 ; ty' <- tcIfaceType ty
887 ; return (mkLocalId name ty') }
889 -----------------------
890 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
891 bindIfaceTyVar (occ,kind) thing_inside
892 = do { name <- newIfaceName occ
893 ; let tyvar = mk_iface_tyvar name kind
894 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
896 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
897 bindIfaceTyVars bndrs thing_inside
898 = do { names <- newIfaceNames occs
899 ; let tyvars = zipWith mk_iface_tyvar names kinds
900 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
902 (occs,kinds) = unzip bndrs
904 mk_iface_tyvar name kind = mkTyVar name (tcIfaceKind kind)