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 loadImportedInsts, loadImportedRules,
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 ( liftedTypeKind, splitTyConApp,
24 mkTyVarTys, mkGenTyConApp, mkTyVarTys, ThetaType, pprClassPred )
25 import TypeRep ( Type(..), PredType(..) )
26 import TyCon ( TyCon, tyConName )
27 import HscTypes ( ExternalPackageState(..), PackageInstEnv, PackageRuleBase,
28 HscEnv, TyThing(..), implicitTyThings, typeEnvIds,
29 ModIface(..), ModDetails(..), InstPool, ModGuts,
30 TypeEnv, mkTypeEnv, extendTypeEnvList, lookupTypeEnv,
32 import InstEnv ( extendInstEnv )
34 import PprCore ( pprIdRules )
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, zipLazy )
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 <- 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 in (eps { eps_PTE = new_type_env }, new_things)
169 ; traceIf (text "tcImport: extend type env" <+> ppr new_things)
172 getThing :: Name -> IfG TyThing
173 -- Find and typecheck the thing; the Name might be a "subordinate name"
174 -- of the "main thing" (e.g. the constructor of a data type declaration)
175 -- The Thing we return is the parent "main thing"
178 | Just thing <- wiredInNameTyThing_maybe name
181 | otherwise = do -- The normal case, not wired in
182 { -- Get the decl from the pool
183 mb_decl <- updateEps (\ eps -> selectDecl eps name)
186 Just decl -> initIfaceLcl (nameModuleName name) (tcIfaceDecl decl)
188 -- Side-effects EPS by faulting in any needed decls
189 -- (via nested calls to tcImportDecl)
192 Nothing -> do { ioToIOEnv (printErrs (msg defaultErrStyle)); failM }
193 -- Declaration not found
194 -- No errors-var to accumulate errors in, so just
195 -- print out the error right now
199 msg = hang (ptext SLIT("Can't find interface-file declaration for") <+> ppr (nameParent name))
200 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
201 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
203 selectDecl :: ExternalPackageState -> Name -> (ExternalPackageState, Maybe IfaceDecl)
204 -- Use nameParent to get the parent name of the thing
205 selectDecl eps@(EPS { eps_decls = Pool decls_map n_in n_out}) name
206 = case lookupNameEnv decls_map main_name of
207 Nothing -> (eps, Nothing)
208 Just decl -> (eps {eps_decls = Pool decls' n_in (n_out+1)}, Just decl)
210 main_name = nameParent name
211 decls' = delFromNameEnv decls_map main_name
214 %************************************************************************
216 Type-checking a complete interface
218 %************************************************************************
220 Suppose we discover we don't need to recompile. Then we must type
221 check the old interface file. This is a bit different to the
222 incremental type checking we do as we suck in interface files. Instead
223 we do things similarly as when we are typechecking source decls: we
224 bring into scope the type envt for the interface all at once, using a
225 knot. Remember, the decls aren't necessarily in dependency order --
226 and even if they were, the type decls might be mutually recursive.
229 typecheckIface :: HscEnv
230 -> ModIface -- Get the decls from here
232 typecheckIface hsc_env iface@(ModIface { mi_module = mod, mi_decls = ver_decls,
233 mi_rules = rules, mi_insts = dfuns })
234 = initIfaceTc hsc_env iface $ \ tc_env_var -> do
235 { -- Typecheck the decls
236 names <- mappM (lookupOrig (moduleName mod) . ifName) decls
237 ; ty_things <- fixM (\ rec_ty_things -> do
238 { writeMutVar tc_env_var (mkNameEnv (names `zipLazy` rec_ty_things))
239 -- This only makes available the "main" things,
240 -- but that's enough for the strictly-checked part
241 ; mapM tcIfaceDecl decls })
243 -- Now augment the type envt with all the implicit things
244 -- These will be needed when type-checking the unfoldings for
245 -- the IfaceIds, but this is done lazily, so writing the thing
247 ; let { add_implicits main_thing = main_thing : implicitTyThings main_thing
248 ; type_env = mkTypeEnv (concatMap add_implicits ty_things) }
249 ; writeMutVar tc_env_var type_env
251 -- Now do those rules and instances
252 ; dfuns <- mapM tcIfaceInst (mi_insts iface)
253 ; rules <- mapM tcIfaceRule (mi_rules iface)
256 ; return (ModDetails { md_types = type_env, md_insts = dfuns, md_rules = rules })
259 decls = map snd ver_decls
263 %************************************************************************
265 Type and class declarations
267 %************************************************************************
269 When typechecking a data type decl, we *lazily* (via forkM) typecheck
270 the constructor argument types. This is in the hope that we may never
271 poke on those argument types, and hence may never need to load the
272 interface files for types mentioned in the arg types.
275 data Foo.S = MkS Baz.T
276 Mabye we can get away without even loading the interface for Baz!
278 This is not just a performance thing. Suppose we have
279 data Foo.S = MkS Baz.T
280 data Baz.T = MkT Foo.S
281 (in different interface files, of course).
282 Now, first we load and typecheck Foo.S, and add it to the type envt.
283 If we do explore MkS's argument, we'll load and typecheck Baz.T.
284 If we explore MkT's argument we'll find Foo.S already in the envt.
286 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
287 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
288 which isn't done yet.
290 All very cunning. However, there is a rather subtle gotcha which bit
291 me when developing this stuff. When we typecheck the decl for S, we
292 extend the type envt with S, MkS, and all its implicit Ids. Suppose
293 (a bug, but it happened) that the list of implicit Ids depended in
294 turn on the constructor arg types. Then the following sequence of
296 * we build a thunk <t> for the constructor arg tys
297 * we build a thunk for the extended type environment (depends on <t>)
298 * we write the extended type envt into the global EPS mutvar
300 Now we look something up in the type envt
302 * which reads the global type envt out of the global EPS mutvar
303 * but that depends in turn on <t>
305 It's subtle, because, it'd work fine if we typechecked the constructor args
306 eagerly -- they don't need the extended type envt. They just get the extended
307 type envt by accident, because they look at it later.
309 What this means is that the implicitTyThings MUST NOT DEPEND on any of
314 tcIfaceDecl :: IfaceDecl -> IfL TyThing
316 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
317 = do { name <- lookupIfaceTop occ_name
318 ; ty <- tcIfaceType iface_type
319 ; info <- tcIdInfo name ty info
320 ; return (AnId (mkVanillaGlobal name ty info)) }
322 tcIfaceDecl (IfaceData {ifND = new_or_data, ifName = occ_name,
323 ifTyVars = tv_bndrs, ifCtxt = rdr_ctxt,
325 ifVrcs = arg_vrcs, ifRec = is_rec,
326 ifGeneric = want_generic })
327 = do { tc_name <- lookupIfaceTop occ_name
328 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
330 { traceIf (text "tcIfaceDecl" <+> ppr rdr_ctxt)
332 ; ctxt <- forkM (ptext SLIT("Ctxt of data decl") <+> ppr tc_name) $
334 -- The reason for laziness here is to postpone
335 -- looking at the context, because the class may not
336 -- be in the type envt yet. E.g.
337 -- class Real a where { toRat :: a -> Ratio Integer }
338 -- data (Real a) => Ratio a = ...
339 -- We suck in the decl for Real, and type check it, which sucks
340 -- in the data type Ratio; but we must postpone typechecking the
343 ; tycon <- fixM ( \ tycon -> do
344 { cons <- tcIfaceDataCons tycon tyvars ctxt rdr_cons
345 ; tycon <- buildAlgTyCon new_or_data tc_name tyvars ctxt cons
346 arg_vrcs is_rec want_generic
349 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
350 ; return (ATyCon tycon)
353 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
354 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
355 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
356 { tc_name <- lookupIfaceTop occ_name
357 ; rhs_ty <- tcIfaceType rdr_rhs_ty
358 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
361 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
362 ifFDs = rdr_fds, ifSigs = rdr_sigs,
363 ifVrcs = tc_vrcs, ifRec = tc_isrec })
364 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
365 { cls_name <- lookupIfaceTop occ_name
366 ; ctxt <- tcIfaceCtxt rdr_ctxt
367 ; sigs <- mappM tc_sig rdr_sigs
368 ; fds <- mappM tc_fd rdr_fds
369 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
370 ; return (AClass cls) }
372 tc_sig (IfaceClassOp occ dm rdr_ty)
373 = do { op_name <- lookupIfaceTop occ
374 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
375 -- Must be done lazily for just the same reason as the
376 -- context of a data decl: the type sig might mention the
377 -- class being defined
378 ; return (op_name, dm, op_ty) }
380 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
382 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
383 ; tvs2' <- mappM tcIfaceTyVar tvs2
384 ; return (tvs1', tvs2') }
386 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
387 = do { name <- lookupIfaceTop rdr_name
388 ; return (ATyCon (mkForeignTyCon name ext_name
389 liftedTypeKind 0 [])) }
391 tcIfaceDataCons tycon tyvars ctxt Unknown
394 tcIfaceDataCons tycon tyvars ctxt (DataCons cs)
395 = mappM tc_con_decl cs `thenM` \ data_cons ->
396 returnM (DataCons data_cons)
398 tc_con_decl (IfaceConDecl occ ex_tvs ex_ctxt args stricts field_lbls)
399 = bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
400 { name <- lookupIfaceTop occ
401 ; ex_theta <- tcIfaceCtxt ex_ctxt -- Laziness seems not worth the bother here
403 -- Read the argument types, but lazily to avoid faulting in
404 -- the component types unless they are really needed
405 ; arg_tys <- forkM (mk_doc name args) (mappM tcIfaceType args) ;
407 ; lbl_names <- mappM lookupIfaceTop field_lbls
409 ; buildDataCon name stricts lbl_names
410 tyvars ctxt ex_tyvars ex_theta
413 mk_doc con_name args = ptext SLIT("Constructor") <+> sep [ppr con_name, ppr args]
417 %************************************************************************
421 %************************************************************************
423 The gating story for instance declarations
424 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
425 When we are looking for a dict (C t1..tn), we slurp in instance decls for
427 mention at least one of the type constructors
428 at the roots of t1..tn
430 Why "at least one" rather than "all"? Because functional dependencies
431 complicate the picture. Consider
432 class C a b | a->b where ...
433 instance C Foo Baz where ...
434 Here, the gates are really only C and Foo, *not* Baz.
435 That is, if C and Foo are visible, even if Baz isn't, we must
436 slurp the decl, even if Baz is thus far completely unknown to the
439 Why "roots of the types"? Reason is overlap. For example, suppose there
440 are interfaces in the pool for
444 Then, if we are trying to resolve (C Int x), we need (a)
445 if we are trying to resolve (C x [y]), we need *both* (b) and (c),
446 even though T is not involved yet, so that we spot the overlap.
449 NOTE: if you use an instance decl with NO type constructors
450 instance C a where ...
451 and look up an Inst that only has type variables such as (C (n o))
452 then GHC won't necessarily suck in the instances that overlap with this.
456 loadImportedInsts :: Class -> [Type] -> TcM PackageInstEnv
457 loadImportedInsts cls tys
458 = do { -- Get interfaces for wired-in things, such as Integer
459 -- Any non-wired-in tycons will already be loaded, else
460 -- we couldn't have them in the Type
461 ; this_mod <- getModule
462 ; let { (cls_gate, tc_gates) = predInstGates cls tys
463 ; imp_wi n = isWiredInName n && this_mod /= nameModule n
464 ; wired_tcs = filter imp_wi tc_gates }
465 -- Wired-in tycons not from this module. The "this-module"
466 -- test bites only when compiling Base etc, because loadHomeInterface
467 -- barfs if it's asked to load a non-existent interface
468 ; if null wired_tcs then returnM ()
469 else initIfaceTcRn (mapM_ (loadHomeInterface wired_doc) wired_tcs)
471 ; eps_var <- getEpsVar
472 ; eps <- readMutVar eps_var
474 -- Suck in the instances
475 ; let { (inst_pool', iface_insts)
476 = WARN( null tc_gates, ptext SLIT("Interesting! No tycons in Inst:")
477 <+> pprClassPred cls tys )
478 selectInsts (eps_insts eps) cls_gate tc_gates }
480 -- Empty => finish up rapidly, without writing to eps
481 ; if null iface_insts then
482 return (eps_inst_env eps)
484 { writeMutVar eps_var (eps {eps_insts = inst_pool'})
486 ; traceIf (sep [ptext SLIT("Importing instances for") <+> pprClassPred cls tys,
487 nest 2 (vcat (map ppr iface_insts))])
489 -- Typecheck the new instances
490 ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
492 -- And put them in the package instance environment
493 ; updateEps ( \ eps ->
495 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
497 (eps { eps_inst_env = inst_env' }, inst_env')
500 wired_doc = ptext SLIT("Need home inteface for wired-in thing")
502 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
504 tcIfaceInst :: IfaceInst -> IfL DFunId
505 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
506 = tcIfaceExtId (LocalTop dfun_occ)
508 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
509 selectInsts pool@(Pool insts n_in n_out) cls tycons
510 = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
512 (insts', iface_insts)
513 = case lookupNameEnv insts cls of {
514 Nothing -> (insts, []) ;
517 case choose1 gated_insts of {
518 (_, []) -> (insts, []) ; -- None picked
519 (gated_insts', iface_insts') ->
521 (extendNameEnv insts cls gated_insts', iface_insts') }}
524 | null tycons -- Bizarre special case of C (a b); then there are no tycons
525 = ([], map snd gated_insts) -- Just grab all the instances, no real alternative
526 | otherwise -- Normal case
527 = foldl choose2 ([],[]) gated_insts
529 -- Reverses the gated decls, but that doesn't matter
530 choose2 (gis, decls) (gates, decl)
531 | null gates -- Happens when we have 'instance T a where ...'
532 || any (`elem` tycons) gates = (gis, decl:decls)
533 | otherwise = ((gates,decl) : gis, decls)
536 %************************************************************************
540 %************************************************************************
542 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
543 are in the type environment. However, remember that typechecking a Rule may
544 (as a side effect) augment the type envt, and so we may need to iterate the process.
547 loadImportedRules :: HscEnv -> ModGuts -> IO PackageRuleBase
548 loadImportedRules hsc_env guts
549 = initIfaceRules hsc_env guts $ do
551 if_rules <- updateEps (\ eps ->
552 let { (new_pool, if_rules) = selectRules (eps_rules eps) (eps_PTE eps) }
553 in (eps { eps_rules = new_pool }, if_rules) )
555 ; traceIf (ptext SLIT("Importing rules:") <+> vcat (map ppr if_rules))
557 ; let tc_rule (mod, rule) = initIfaceLcl mod (tcIfaceRule rule)
558 ; core_rules <- mapM tc_rule if_rules
561 ; traceIf (ptext SLIT("Imported rules:") <+> pprIdRules core_rules)
563 -- Update the rule base and return it
564 ; updateEps (\ eps ->
565 let { new_rule_base = extendRuleBaseList (eps_rule_base eps) core_rules }
566 in (eps { eps_rule_base = new_rule_base }, new_rule_base)
569 -- Strictly speaking, at this point we should go round again, since
570 -- typechecking one set of rules may bring in new things which enable
571 -- some more rules to come in. But we call loadImportedRules several
572 -- times anyway, so I'm going to be lazy and ignore this.
576 selectRules :: RulePool -> TypeEnv -> (RulePool, [(ModuleName, IfaceRule)])
577 -- Not terribly efficient. Look at each rule in the pool to see if
578 -- all its gates are in the type env. If so, take it out of the pool.
579 -- If not, trim its gates for next time.
580 selectRules (Pool rules n_in n_out) type_env
581 = (Pool rules' n_in (n_out + length if_rules), if_rules)
583 (rules', if_rules) = foldl do_one ([], []) rules
585 do_one (pool, if_rules) (gates, rule)
586 | null gates' = (pool, rule:if_rules)
587 | otherwise = ((gates',rule) : pool, if_rules)
589 gates' = filter (not . (`elemNameEnv` type_env)) gates
592 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
593 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
594 ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
595 = bindIfaceBndrs bndrs $ \ bndrs' ->
596 do { fn <- tcIfaceExtId fn_rdr
597 ; args' <- mappM tcIfaceExpr args
598 ; rhs' <- tcIfaceExpr rhs
599 ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
601 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
602 = do { fn <- tcIfaceExtId fn_rdr
603 ; returnM (fn, core_rule) }
607 %************************************************************************
611 %************************************************************************
614 tcIfaceType :: IfaceType -> IfL Type
615 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
616 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
617 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
618 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
619 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
620 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
622 tcIfaceTypes tys = mapM tcIfaceType tys
624 -----------------------------------------
625 tcIfacePredType :: IfacePredType -> IfL PredType
626 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
627 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
629 -----------------------------------------
630 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
631 tcIfaceCtxt sts = mappM tcIfacePredType sts
635 %************************************************************************
639 %************************************************************************
642 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
643 tcIfaceExpr (IfaceType ty)
644 = tcIfaceType ty `thenM` \ ty' ->
647 tcIfaceExpr (IfaceLcl name)
648 = tcIfaceLclId name `thenM` \ id ->
651 tcIfaceExpr (IfaceExt gbl)
652 = tcIfaceExtId gbl `thenM` \ id ->
655 tcIfaceExpr (IfaceLit lit)
658 tcIfaceExpr (IfaceFCall cc ty)
659 = tcIfaceType ty `thenM` \ ty' ->
660 newUnique `thenM` \ u ->
661 returnM (Var (mkFCallId u cc ty'))
663 tcIfaceExpr (IfaceTuple boxity args)
664 = mappM tcIfaceExpr args `thenM` \ args' ->
666 -- Put the missing type arguments back in
667 con_args = map (Type . exprType) args' ++ args'
669 returnM (mkApps (Var con_id) con_args)
672 con_id = dataConWorkId (tupleCon boxity arity)
675 tcIfaceExpr (IfaceLam bndr body)
676 = bindIfaceBndr bndr $ \ bndr' ->
677 tcIfaceExpr body `thenM` \ body' ->
678 returnM (Lam bndr' body')
680 tcIfaceExpr (IfaceApp fun arg)
681 = tcIfaceExpr fun `thenM` \ fun' ->
682 tcIfaceExpr arg `thenM` \ arg' ->
683 returnM (App fun' arg')
685 tcIfaceExpr (IfaceCase scrut case_bndr alts)
686 = tcIfaceExpr scrut `thenM` \ scrut' ->
687 newIfaceName case_bndr `thenM` \ case_bndr_name ->
689 scrut_ty = exprType scrut'
690 case_bndr' = mkLocalId case_bndr_name scrut_ty
691 tc_app = splitTyConApp scrut_ty
692 -- NB: Won't always succeed (polymoprhic case)
693 -- but won't be demanded in those cases
694 -- NB: not tcSplitTyConApp; we are looking at Core here
695 -- look through non-rec newtypes to find the tycon that
696 -- corresponds to the datacon in this case alternative
698 extendIfaceIdEnv [case_bndr'] $
699 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
700 returnM (Case scrut' case_bndr' alts')
702 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
703 = tcIfaceExpr rhs `thenM` \ rhs' ->
704 bindIfaceId bndr $ \ bndr' ->
705 tcIfaceExpr body `thenM` \ body' ->
706 returnM (Let (NonRec bndr' rhs') body')
708 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
709 = bindIfaceIds bndrs $ \ bndrs' ->
710 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
711 tcIfaceExpr body `thenM` \ body' ->
712 returnM (Let (Rec (bndrs' `zip` rhss')) body')
714 (bndrs, rhss) = unzip pairs
716 tcIfaceExpr (IfaceNote note expr)
717 = tcIfaceExpr expr `thenM` \ expr' ->
719 IfaceCoerce to_ty -> tcIfaceType to_ty `thenM` \ to_ty' ->
720 returnM (Note (Coerce to_ty'
721 (exprType expr')) expr')
722 IfaceInlineCall -> returnM (Note InlineCall expr')
723 IfaceInlineMe -> returnM (Note InlineMe expr')
724 IfaceSCC cc -> returnM (Note (SCC cc) expr')
725 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
727 -------------------------
728 tcIfaceAlt _ (IfaceDefault, names, rhs)
729 = ASSERT( null names )
730 tcIfaceExpr rhs `thenM` \ rhs' ->
731 returnM (DEFAULT, [], rhs')
733 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
734 = ASSERT( null names )
735 tcIfaceExpr rhs `thenM` \ rhs' ->
736 returnM (LitAlt lit, [], rhs')
738 -- A case alternative is made quite a bit more complicated
739 -- by the fact that we omit type annotations because we can
740 -- work them out. True enough, but its not that easy!
741 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
743 tycon_mod = nameModuleName (tyConName tycon)
745 tcIfaceDataCon (ExtPkg tycon_mod data_occ) `thenM` \ con ->
746 newIfaceNames arg_occs `thenM` \ arg_names ->
748 ex_tyvars = dataConExistentialTyVars con
749 main_tyvars = tyConTyVars tycon
750 ex_tyvars' = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars]
751 ex_tys' = mkTyVarTys ex_tyvars'
752 arg_tys = dataConArgTys con (inst_tys ++ ex_tys')
753 id_names = dropList ex_tyvars arg_names
756 | not (equalLength id_names arg_tys)
757 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
758 (ppr main_tyvars <+> ppr ex_tyvars) $$
762 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
764 ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
765 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$ ppr main_tyvars )
766 extendIfaceTyVarEnv ex_tyvars' $
767 extendIfaceIdEnv arg_ids $
768 tcIfaceExpr rhs `thenM` \ rhs' ->
769 returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
771 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
772 = newIfaceNames arg_occs `thenM` \ arg_names ->
774 [con] = tyConDataCons tycon
775 arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
777 ASSERT( isTupleTyCon tycon )
778 extendIfaceIdEnv arg_ids $
779 tcIfaceExpr rhs `thenM` \ rhs' ->
780 returnM (DataAlt con, arg_ids, rhs')
785 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
786 tcExtCoreBindings mod [] = return []
787 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
789 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
790 do_one mod (IfaceNonRec bndr rhs) thing_inside
791 = do { rhs' <- tcIfaceExpr rhs
792 ; bndr' <- newExtCoreBndr mod bndr
793 ; extendIfaceIdEnv [bndr'] $ do
794 { core_binds <- thing_inside
795 ; return (NonRec bndr' rhs' : core_binds) }}
797 do_one mod (IfaceRec pairs) thing_inside
798 = do { bndrs' <- mappM (newExtCoreBndr mod) bndrs
799 ; extendIfaceIdEnv bndrs' $ do
800 { rhss' <- mappM tcIfaceExpr rhss
801 ; core_binds <- thing_inside
802 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
804 (bndrs,rhss) = unzip pairs
808 %************************************************************************
812 %************************************************************************
815 tcIdInfo name ty NoInfo = return vanillaIdInfo
816 tcIdInfo name ty DiscardedInfo = return vanillaIdInfo
817 tcIdInfo name ty (HasInfo iface_info)
818 = foldlM tcPrag init_info iface_info
820 -- Set the CgInfo to something sensible but uninformative before
821 -- we start; default assumption is that it has CAFs
822 init_info = vanillaIdInfo
824 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
825 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
826 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
828 -- The next two are lazy, so they don't transitively suck stuff in
829 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
830 tcPrag info (HsUnfold inline_prag expr)
831 = tcPragExpr name expr `thenM` \ maybe_expr' ->
833 -- maybe_expr' doesn't get looked at if the unfolding
834 -- is never inspected; so the typecheck doesn't even happen
835 unfold_info = case maybe_expr' of
836 Nothing -> noUnfolding
837 Just expr' -> mkTopUnfolding expr'
839 returnM (info `setUnfoldingInfoLazily` unfold_info
840 `setInlinePragInfo` inline_prag)
844 tcWorkerInfo ty info wkr_name arity
845 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
847 -- We return without testing maybe_wkr_id, but as soon as info is
848 -- looked at we will test it. That's ok, because its outside the
849 -- knot; and there seems no big reason to further defer the
850 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
851 -- over the unfolding until it's actually used does seem worth while.)
852 ; us <- newUniqueSupply
854 ; returnM (case mb_wkr_id of
856 Just wkr_id -> add_wkr_info us wkr_id info) }
858 doc = text "Worker for" <+> ppr wkr_name
859 add_wkr_info us wkr_id info
860 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
861 `setWorkerInfo` HasWorker wkr_id arity
863 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
865 -- We are relying here on strictness info always appearing
866 -- before worker info, fingers crossed ....
867 strict_sig = case newStrictnessInfo info of
869 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
872 For unfoldings we try to do the job lazily, so that we never type check
873 an unfolding that isn't going to be looked at.
876 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
879 tcIfaceExpr expr `thenM` \ core_expr' ->
881 -- Check for type consistency in the unfolding
882 ifOptM Opt_DoCoreLinting (
883 get_in_scope_ids `thenM` \ in_scope ->
884 case lintUnfolding noSrcLoc in_scope core_expr' of
885 Nothing -> returnM ()
886 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
891 doc = text "Unfolding of" <+> ppr name
892 get_in_scope_ids -- Urgh; but just for linting
894 do { env <- getGblEnv
895 ; case if_rec_types env of {
896 Nothing -> return [] ;
897 Just (_, get_env) -> do
898 { type_env <- get_env
899 ; return (typeEnvIds type_env) }}}
904 %************************************************************************
908 %************************************************************************
911 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
912 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
913 = bindIfaceId bndr thing_inside
914 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
915 = bindIfaceTyVar bndr thing_inside
917 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
918 bindIfaceBndrs [] thing_inside = thing_inside []
919 bindIfaceBndrs (b:bs) thing_inside
920 = bindIfaceBndr b $ \ b' ->
921 bindIfaceBndrs bs $ \ bs' ->
922 thing_inside (b':bs')
924 -----------------------
925 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
926 bindIfaceId (occ, ty) thing_inside
927 = do { name <- newIfaceName occ
928 ; ty' <- tcIfaceType ty
929 ; let { id = mkLocalId name ty' }
930 ; extendIfaceIdEnv [id] (thing_inside id) }
932 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
933 bindIfaceIds bndrs thing_inside
934 = do { names <- newIfaceNames occs
935 ; tys' <- mappM tcIfaceType tys
936 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
937 ; extendIfaceIdEnv ids (thing_inside ids) }
939 (occs,tys) = unzip bndrs
942 -----------------------
943 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
944 newExtCoreBndr mod (occ, ty)
945 = do { name <- newGlobalBinder mod occ Nothing noSrcLoc
946 ; ty' <- tcIfaceType ty
947 ; return (mkLocalId name ty') }
949 -----------------------
950 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
951 bindIfaceTyVar (occ,kind) thing_inside
952 = do { name <- newIfaceName occ
953 ; let tyvar = mk_iface_tyvar name kind
954 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
956 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
957 bindIfaceTyVars bndrs thing_inside
958 = do { names <- newIfaceNames occs
959 ; let tyvars = zipWith mk_iface_tyvar names kinds
960 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
962 (occs,kinds) = unzip bndrs
964 mk_iface_tyvar name kind = mkTyVar name kind