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, typeEnvIds,
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 }
115 ; traceIf (nd_doc <+> char '{') -- Brace matches the later message
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-committal 'Nothing'
120 -- in 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 <+> char '}')
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 ; traceIf (text "tcImport: rules" <+> vcat (map ppr iface_rules))
177 ; core_rules <- mapM tc_rule iface_rules
178 ; updateEps_ (\ eps ->
179 eps { eps_rule_base = extendRuleBaseList (eps_rule_base eps) core_rules }
182 tc_rule (mod, rule) = initIfaceLcl mod (tcIfaceRule rule)
184 getThing :: Name -> IfG TyThing
185 -- Find and typecheck the thing; the Name might be a "subordinate name"
186 -- of the "main thing" (e.g. the constructor of a data type declaration)
187 -- The Thing we return is the parent "main thing"
190 | Just thing <- wiredInNameTyThing_maybe name
193 | otherwise = do -- The normal case, not wired in
194 { -- Get the decl from the pool
195 decl <- updateEps (\ eps ->
197 (decls', decl) = selectDecl (eps_decls eps) name
199 (eps { eps_decls = decls' }, decl))
202 -- Side-effects EPS by faulting in any needed decls
203 -- (via nested calls to tcImportDecl)
204 ; initIfaceLcl (nameModuleName name) (tcIfaceDecl decl) }
207 selectDecl :: DeclPool -> Name -> (DeclPool, IfaceDecl)
208 -- Use nameParent to get the parent name of the thing
209 selectDecl (Pool decls_map n_in n_out) name
210 = (Pool decls' n_in (n_out+1), decl)
212 main_name = nameParent name
213 decl = case lookupNameEnv decls_map main_name of
214 Nothing -> pprPanic "selectDecl" (ppr main_name <+> ppr name) ;
217 decls' = delFromNameEnv decls_map main_name
220 %************************************************************************
224 %************************************************************************
227 typecheckIface :: ModIface -> IfG ModDetails
228 -- Used when we decide not to recompile, but intead to use the
229 -- interface to construct the type environment for the module
231 = initIfaceLcl (moduleName (mi_module iface)) $
232 do { ty_things <- mapM (tcIfaceDecl . snd) (mi_decls iface)
233 ; rules <- mapM tcIfaceRule (mi_rules iface)
234 ; dfuns <- mapM tcIfaceInst (mi_insts iface)
235 ; return (ModDetails { md_types = mkTypeEnv ty_things,
237 md_rules = rules }) }
241 %************************************************************************
243 Type and class declarations
245 %************************************************************************
247 When typechecking a data type decl, we *lazily* (via forkM) typecheck
248 the constructor argument types. This is in the hope that we may never
249 poke on those argument types, and hence may never need to load the
250 interface files for types mentioned in the arg types.
253 data Foo.S = MkS Baz.T
254 Mabye we can get away without even loading the interface for Baz!
256 This is not just a performance thing. Suppose we have
257 data Foo.S = MkS Baz.T
258 data Baz.T = MkT Foo.S
259 (in different interface files, of course).
260 Now, first we load and typecheck Foo.S, and add it to the type envt.
261 If we do explore MkS's argument, we'll load and typecheck Baz.T.
262 If we explore MkT's argument we'll find Foo.S already in the envt.
264 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
265 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
266 which isn't done yet.
268 All very cunning. However, there is a rather subtle gotcha which bit
269 me when developing this stuff. When we typecheck the decl for S, we
270 extend the type envt with S, MkS, and all its implicit Ids. Suppose
271 (a bug, but it happened) that the list of implicit Ids depended in
272 turn on the constructor arg types. Then the following sequence of
274 * we build a thunk <t> for the constructor arg tys
275 * we build a thunk for the extended type environment (depends on <t>)
276 * we write the extended type envt into the global EPS mutvar
278 Now we look something up in the type envt
280 * which reads the global type envt out of the global EPS mutvar
281 * but that depends in turn on <t>
283 It's subtle, because, it'd work fine if we typechecked the constructor args
284 eagerly -- they don't need the extended type envt. They just get the extended
285 type envt by accident, because they look at it later.
287 What this means is that the implicitTyThings MUST NOT DEPEND on any of
292 tcIfaceDecl :: IfaceDecl -> IfL TyThing
294 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
295 = do { name <- lookupIfaceTop occ_name
296 ; ty <- tcIfaceType iface_type
297 ; info <- tcIdInfo name ty info
298 ; return (AnId (mkVanillaGlobal name ty info)) }
300 tcIfaceDecl (IfaceData {ifND = new_or_data, ifName = occ_name,
301 ifTyVars = tv_bndrs, ifCtxt = rdr_ctxt,
303 ifVrcs = arg_vrcs, ifRec = is_rec,
304 ifGeneric = want_generic })
305 = do { tc_name <- lookupIfaceTop occ_name
306 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
308 { traceIf (text "tcIfaceDecl" <+> ppr rdr_ctxt)
310 ; ctxt <- forkM (ptext SLIT("Ctxt of data decl") <+> ppr tc_name) $
312 -- The reason for laziness here is to postpone
313 -- looking at the context, because the class may not
314 -- be in the type envt yet. E.g.
315 -- class Real a where { toRat :: a -> Ratio Integer }
316 -- data (Real a) => Ratio a = ...
317 -- We suck in the decl for Real, and type check it, which sucks
318 -- in the data type Ratio; but we must postpone typechecking the
321 ; tycon <- fixM ( \ tycon -> do
322 { cons <- tcIfaceDataCons tycon tyvars ctxt rdr_cons
323 ; tycon <- buildAlgTyCon new_or_data tc_name tyvars ctxt cons
324 arg_vrcs is_rec want_generic
327 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
328 ; return (ATyCon tycon)
331 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
332 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
333 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
334 { tc_name <- lookupIfaceTop occ_name
335 ; rhs_ty <- tcIfaceType rdr_rhs_ty
336 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
339 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
340 ifFDs = rdr_fds, ifSigs = rdr_sigs,
341 ifVrcs = tc_vrcs, ifRec = tc_isrec })
342 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
343 { cls_name <- lookupIfaceTop occ_name
344 ; ctxt <- tcIfaceCtxt rdr_ctxt
345 ; sigs <- mappM tc_sig rdr_sigs
346 ; fds <- mappM tc_fd rdr_fds
347 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
348 ; return (AClass cls) }
350 tc_sig (IfaceClassOp occ dm rdr_ty)
351 = do { op_name <- lookupIfaceTop occ
352 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
353 -- Must be done lazily for just the same reason as the
354 -- context of a data decl: the type sig might mention the
355 -- class being defined
356 ; return (op_name, dm, op_ty) }
358 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
360 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
361 ; tvs2' <- mappM tcIfaceTyVar tvs2
362 ; return (tvs1', tvs2') }
364 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
365 = do { name <- lookupIfaceTop rdr_name
366 ; return (ATyCon (mkForeignTyCon name ext_name
367 liftedTypeKind 0 [])) }
369 tcIfaceDataCons tycon tyvars ctxt Unknown
372 tcIfaceDataCons tycon tyvars ctxt (DataCons cs)
373 = mappM tc_con_decl cs `thenM` \ data_cons ->
374 returnM (DataCons data_cons)
376 tc_con_decl (IfaceConDecl occ ex_tvs ex_ctxt args stricts field_lbls)
377 = bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
378 { name <- lookupIfaceTop occ
379 ; ex_theta <- tcIfaceCtxt ex_ctxt -- Laziness seems not worth the bother here
381 -- Read the argument types, but lazily to avoid faulting in
382 -- the component types unless they are really needed
383 ; arg_tys <- forkM (mk_doc name args) (mappM tcIfaceType args) ;
385 ; lbl_names <- mappM lookupIfaceTop field_lbls
387 ; buildDataCon name stricts lbl_names
388 tyvars ctxt ex_tyvars ex_theta
391 mk_doc con_name args = ptext SLIT("Constructor") <+> sep [ppr con_name, ppr args]
395 %************************************************************************
399 %************************************************************************
401 The gating story for instance declarations
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403 When we are looking for a dict (C t1..tn), we slurp in instance decls for
405 mention at least one of the type constructors
406 at the roots of t1..tn
408 Why "at least one" rather than "all"? Because functional dependencies
409 complicate the picture. Consider
410 class C a b | a->b where ...
411 instance C Foo Baz where ...
412 Here, the gates are really only C and Foo, *not* Baz.
413 That is, if C and Foo are visible, even if Baz isn't, we must
414 slurp the decl, even if Baz is thus far completely unknown to the
417 Why "roots of the types"? Reason is overlap. For example, suppose there
418 are interfaces in the pool for
422 Then, if we are trying to resolve (C Int x), we need (a)
423 if we are trying to resolve (C x [y]), we need *both* (b) and (c),
424 even though T is not involved yet, so that we spot the overlap.
427 loadImportedInsts :: Class -> [Type] -> TcM PackageInstEnv
428 loadImportedInsts cls tys
429 = do { -- Get interfaces for wired-in things, such as Integer
430 -- Any non-wired-in tycons will already be loaded, else
431 -- we couldn't have them in the Type
432 ; this_mod <- getModule
433 ; let { (cls_gate, tc_gates) = predInstGates cls tys
434 ; imp_wi n = isWiredInName n && this_mod /= nameModule n
435 ; wired_tcs = filter imp_wi tc_gates }
436 -- Wired-in tycons not from this module. The "this-module"
437 -- test bites only when compiling Base etc, because loadHomeInterface
438 -- barfs if it's asked to load a non-existent interface
439 ; if null wired_tcs then returnM ()
440 else initIfaceTcRn (mapM_ (loadHomeInterface wired_doc) wired_tcs)
442 ; eps_var <- getEpsVar
443 ; eps <- readMutVar eps_var
445 -- Suck in the instances
446 ; let { (inst_pool', iface_insts)
447 = selectInsts (eps_insts eps) cls_gate tc_gates }
449 -- Empty => finish up rapidly, without writing to eps
450 ; if null iface_insts then
451 return (eps_inst_env eps)
453 { writeMutVar eps_var (eps {eps_insts = inst_pool'})
455 -- Typecheck the new instances
456 ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
458 -- And put them in the package instance environment
459 ; updateEps ( \ eps ->
461 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
463 (eps { eps_inst_env = inst_env' }, inst_env')
466 wired_doc = ptext SLIT("Need home inteface for wired-in thing")
468 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
470 tcIfaceInst :: IfaceInst -> IfL DFunId
471 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
472 = tcIfaceExtId (LocalTop dfun_occ)
474 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
475 selectInsts pool@(Pool insts n_in n_out) cls tycons
476 = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
478 (insts', iface_insts)
479 = case lookupNameEnv insts cls of {
480 Nothing -> (insts, []) ;
483 case foldl choose ([],[]) gated_insts of {
484 (_, []) -> (insts, []) ; -- None picked
485 (gated_insts', iface_insts') ->
487 (extendNameEnv insts cls gated_insts', iface_insts') }}
489 -- Reverses the gated decls, but that doesn't matter
490 choose (gis, decls) (gates, decl)
491 | any (`elem` tycons) gates = (gis, decl:decls)
492 | otherwise = ((gates,decl) : gis, decls)
495 %************************************************************************
499 %************************************************************************
501 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
502 are in the type environment. However, remember that typechecking a Rule may
503 (as a side effect) augment the type envt, and so we may need to iterate the process.
506 selectRules :: RulePool
507 -> [Name] -- Names of things being added
508 -> TypeEnv -- New type env, including things being added
509 -> (RulePool, [(ModuleName, IfaceRule)])
510 selectRules (Pool rules n_in n_out) new_names type_env
511 = (Pool rules' n_in (n_out + length iface_rules), iface_rules)
513 (rules', iface_rules) = foldl select_one (rules, []) new_names
515 select_one :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Name
516 -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
517 select_one (rules, decls) name
518 = case lookupNameEnv rules name of
519 Nothing -> (rules, decls)
520 Just gated_rules -> foldl filter_rule (delFromNameEnv rules name, decls) gated_rules
522 filter_rule :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Gated IfaceRule
523 -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
524 filter_rule (rules, decls) (rule_fvs, rule)
525 = case [fv | fv <- rule_fvs, not (fv `elemNameEnv` type_env)] of
526 [] -> -- No remaining FVs, so slurp it
528 fvs -> -- There leftover fvs, so toss it back in the pool
529 (addRuleToPool rules rule fvs, decls)
531 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
532 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
533 ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
534 = bindIfaceBndrs bndrs $ \ bndrs' ->
535 do { fn <- tcIfaceExtId fn_rdr
536 ; args' <- mappM tcIfaceExpr args
537 ; rhs' <- tcIfaceExpr rhs
538 ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
540 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
541 = do { fn <- tcIfaceExtId fn_rdr
542 ; returnM (fn, core_rule) }
546 %************************************************************************
550 %************************************************************************
553 tcIfaceKind :: IfaceKind -> Kind
554 tcIfaceKind IfaceOpenTypeKind = openTypeKind
555 tcIfaceKind IfaceLiftedTypeKind = liftedTypeKind
556 tcIfaceKind IfaceUnliftedTypeKind = unliftedTypeKind
557 tcIfaceKind (IfaceFunKind k1 k2) = mkArrowKind (tcIfaceKind k1) (tcIfaceKind k2)
559 -----------------------------------------
560 tcIfaceType :: IfaceType -> IfL Type
561 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
562 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
563 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
564 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
565 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
566 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
568 tcIfaceTypes tys = mapM tcIfaceType tys
570 -----------------------------------------
571 tcIfacePredType :: IfacePredType -> IfL PredType
572 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
573 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
575 -----------------------------------------
576 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
577 tcIfaceCtxt sts = mappM tcIfacePredType sts
581 %************************************************************************
585 %************************************************************************
588 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
589 tcIfaceExpr (IfaceType ty)
590 = tcIfaceType ty `thenM` \ ty' ->
593 tcIfaceExpr (IfaceLcl name)
594 = tcIfaceLclId name `thenM` \ id ->
597 tcIfaceExpr (IfaceExt gbl)
598 = tcIfaceExtId gbl `thenM` \ id ->
601 tcIfaceExpr (IfaceLit lit)
604 tcIfaceExpr (IfaceFCall cc ty)
605 = tcIfaceType ty `thenM` \ ty' ->
606 newUnique `thenM` \ u ->
607 returnM (Var (mkFCallId u cc ty'))
609 tcIfaceExpr (IfaceTuple boxity args)
610 = mappM tcIfaceExpr args `thenM` \ args' ->
612 -- Put the missing type arguments back in
613 con_args = map (Type . exprType) args' ++ args'
615 returnM (mkApps (Var con_id) con_args)
618 con_id = dataConWorkId (tupleCon boxity arity)
621 tcIfaceExpr (IfaceLam bndr body)
622 = bindIfaceBndr bndr $ \ bndr' ->
623 tcIfaceExpr body `thenM` \ body' ->
624 returnM (Lam bndr' body')
626 tcIfaceExpr (IfaceApp fun arg)
627 = tcIfaceExpr fun `thenM` \ fun' ->
628 tcIfaceExpr arg `thenM` \ arg' ->
629 returnM (App fun' arg')
631 tcIfaceExpr (IfaceCase scrut case_bndr alts)
632 = tcIfaceExpr scrut `thenM` \ scrut' ->
633 newIfaceName case_bndr `thenM` \ case_bndr_name ->
635 scrut_ty = exprType scrut'
636 case_bndr' = mkLocalId case_bndr_name scrut_ty
637 tc_app = splitTyConApp scrut_ty
638 -- NB: Won't always succeed (polymoprhic case)
639 -- but won't be demanded in those cases
640 -- NB: not tcSplitTyConApp; we are looking at Core here
641 -- look through non-rec newtypes to find the tycon that
642 -- corresponds to the datacon in this case alternative
644 extendIfaceIdEnv [case_bndr'] $
645 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
646 returnM (Case scrut' case_bndr' alts')
648 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
649 = tcIfaceExpr rhs `thenM` \ rhs' ->
650 bindIfaceId bndr $ \ bndr' ->
651 tcIfaceExpr body `thenM` \ body' ->
652 returnM (Let (NonRec bndr' rhs') body')
654 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
655 = bindIfaceIds bndrs $ \ bndrs' ->
656 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
657 tcIfaceExpr body `thenM` \ body' ->
658 returnM (Let (Rec (bndrs' `zip` rhss')) body')
660 (bndrs, rhss) = unzip pairs
662 tcIfaceExpr (IfaceNote note expr)
663 = tcIfaceExpr expr `thenM` \ expr' ->
665 IfaceCoerce to_ty -> tcIfaceType to_ty `thenM` \ to_ty' ->
666 returnM (Note (Coerce to_ty'
667 (exprType expr')) expr')
668 IfaceInlineCall -> returnM (Note InlineCall expr')
669 IfaceInlineMe -> returnM (Note InlineMe expr')
670 IfaceSCC cc -> returnM (Note (SCC cc) expr')
671 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
673 -------------------------
674 tcIfaceAlt _ (IfaceDefault, names, rhs)
675 = ASSERT( null names )
676 tcIfaceExpr rhs `thenM` \ rhs' ->
677 returnM (DEFAULT, [], rhs')
679 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
680 = ASSERT( null names )
681 tcIfaceExpr rhs `thenM` \ rhs' ->
682 returnM (LitAlt lit, [], rhs')
684 -- A case alternative is made quite a bit more complicated
685 -- by the fact that we omit type annotations because we can
686 -- work them out. True enough, but its not that easy!
687 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
689 tycon_mod = nameModuleName (tyConName tycon)
691 tcIfaceDataCon (ExtPkg tycon_mod data_occ) `thenM` \ con ->
692 newIfaceNames arg_occs `thenM` \ arg_names ->
694 ex_tyvars = dataConExistentialTyVars con
695 main_tyvars = tyConTyVars tycon
696 ex_tyvars' = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars]
697 ex_tys' = mkTyVarTys ex_tyvars'
698 arg_tys = dataConArgTys con (inst_tys ++ ex_tys')
699 id_names = dropList ex_tyvars arg_names
702 | not (equalLength id_names arg_tys)
703 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
704 (ppr main_tyvars <+> ppr ex_tyvars) $$
708 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
710 ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
711 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$ ppr main_tyvars )
712 extendIfaceTyVarEnv ex_tyvars' $
713 extendIfaceIdEnv arg_ids $
714 tcIfaceExpr rhs `thenM` \ rhs' ->
715 returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
717 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
718 = newIfaceNames arg_occs `thenM` \ arg_names ->
720 [con] = tyConDataCons tycon
721 arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
723 ASSERT( isTupleTyCon tycon )
724 extendIfaceIdEnv arg_ids $
725 tcIfaceExpr rhs `thenM` \ rhs' ->
726 returnM (DataAlt con, arg_ids, rhs')
731 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
732 tcExtCoreBindings mod [] = return []
733 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
735 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
736 do_one mod (IfaceNonRec bndr rhs) thing_inside
737 = do { rhs' <- tcIfaceExpr rhs
738 ; bndr' <- newExtCoreBndr mod bndr
739 ; extendIfaceIdEnv [bndr'] $ do
740 { core_binds <- thing_inside
741 ; return (NonRec bndr' rhs' : core_binds) }}
743 do_one mod (IfaceRec pairs) thing_inside
744 = do { bndrs' <- mappM (newExtCoreBndr mod) bndrs
745 ; extendIfaceIdEnv bndrs' $ do
746 { rhss' <- mappM tcIfaceExpr rhss
747 ; core_binds <- thing_inside
748 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
750 (bndrs,rhss) = unzip pairs
754 %************************************************************************
758 %************************************************************************
761 tcIdInfo name ty NoInfo = return vanillaIdInfo
762 tcIdInfo name ty DiscardedInfo = return vanillaIdInfo
763 tcIdInfo name ty (HasInfo iface_info)
764 = foldlM tcPrag init_info iface_info
766 -- Set the CgInfo to something sensible but uninformative before
767 -- we start; default assumption is that it has CAFs
768 init_info = vanillaIdInfo
770 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
771 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
772 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
774 -- The next two are lazy, so they don't transitively suck stuff in
775 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
776 tcPrag info (HsUnfold inline_prag expr)
777 = tcPragExpr name expr `thenM` \ maybe_expr' ->
779 -- maybe_expr' doesn't get looked at if the unfolding
780 -- is never inspected; so the typecheck doesn't even happen
781 unfold_info = case maybe_expr' of
782 Nothing -> noUnfolding
783 Just expr' -> mkTopUnfolding expr'
785 returnM (info `setUnfoldingInfoLazily` unfold_info
786 `setInlinePragInfo` inline_prag)
790 tcWorkerInfo ty info wkr_name arity
791 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
793 -- We return without testing maybe_wkr_id, but as soon as info is
794 -- looked at we will test it. That's ok, because its outside the
795 -- knot; and there seems no big reason to further defer the
796 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
797 -- over the unfolding until it's actually used does seem worth while.)
798 ; us <- newUniqueSupply
800 ; returnM (case mb_wkr_id of
802 Just wkr_id -> add_wkr_info us wkr_id info) }
804 doc = text "Worker for" <+> ppr wkr_name
805 add_wkr_info us wkr_id info
806 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
807 `setWorkerInfo` HasWorker wkr_id arity
809 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
811 -- We are relying here on strictness info always appearing
812 -- before worker info, fingers crossed ....
813 strict_sig = case newStrictnessInfo info of
815 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
818 For unfoldings we try to do the job lazily, so that we never type check
819 an unfolding that isn't going to be looked at.
822 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
825 tcIfaceExpr expr `thenM` \ core_expr' ->
827 -- Check for type consistency in the unfolding
828 ifOptM Opt_DoCoreLinting (
829 get_in_scope_ids `thenM` \ in_scope ->
830 case lintUnfolding noSrcLoc in_scope core_expr' of
831 Nothing -> returnM ()
832 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
837 doc = text "Unfolding of" <+> ppr name
838 get_in_scope_ids -- Urgh; but just for linting
840 do { env <- getGblEnv
841 ; case if_rec_types env of {
842 Nothing -> return [] ;
843 Just (_, get_env) -> do
844 { type_env <- get_env
845 ; return (typeEnvIds type_env) }}}
850 %************************************************************************
854 %************************************************************************
857 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
858 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
859 = bindIfaceId bndr thing_inside
860 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
861 = bindIfaceTyVar bndr thing_inside
863 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
864 bindIfaceBndrs [] thing_inside = thing_inside []
865 bindIfaceBndrs (b:bs) thing_inside
866 = bindIfaceBndr b $ \ b' ->
867 bindIfaceBndrs bs $ \ bs' ->
868 thing_inside (b':bs')
870 -----------------------
871 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
872 bindIfaceId (occ, ty) thing_inside
873 = do { name <- newIfaceName occ
874 ; ty' <- tcIfaceType ty
875 ; let { id = mkLocalId name ty' }
876 ; extendIfaceIdEnv [id] (thing_inside id) }
878 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
879 bindIfaceIds bndrs thing_inside
880 = do { names <- newIfaceNames occs
881 ; tys' <- mappM tcIfaceType tys
882 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
883 ; extendIfaceIdEnv ids (thing_inside ids) }
885 (occs,tys) = unzip bndrs
888 -----------------------
889 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
890 newExtCoreBndr mod (occ, ty)
891 = do { name <- newGlobalBinder mod occ Nothing noSrcLoc
892 ; ty' <- tcIfaceType ty
893 ; return (mkLocalId name ty') }
895 -----------------------
896 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
897 bindIfaceTyVar (occ,kind) thing_inside
898 = do { name <- newIfaceName occ
899 ; let tyvar = mk_iface_tyvar name kind
900 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
902 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
903 bindIfaceTyVars bndrs thing_inside
904 = do { names <- newIfaceNames occs
905 ; let tyvars = zipWith mk_iface_tyvar names kinds
906 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
908 (occs,kinds) = unzip bndrs
910 mk_iface_tyvar name kind = mkTyVar name (tcIfaceKind kind)