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,
22 mkAbstractTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
24 import Type ( liftedTypeKind, splitTyConApp,
25 mkTyVarTys, mkGenTyConApp, mkTyVarTys, ThetaType, pprClassPred )
26 import TypeRep ( Type(..), PredType(..) )
27 import TyCon ( TyCon, tyConName )
28 import HscTypes ( ExternalPackageState(..), PackageInstEnv, PackageRuleBase,
29 HscEnv, TyThing(..), implicitTyThings, typeEnvIds,
30 ModIface(..), ModDetails(..), InstPool, ModGuts,
31 TypeEnv, mkTypeEnv, extendTypeEnvList, lookupTypeEnv,
33 import InstEnv ( extendInstEnv )
35 import PprCore ( pprIdRules )
36 import Rules ( extendRuleBaseList )
37 import CoreUtils ( exprType )
39 import CoreLint ( lintUnfolding )
40 import WorkWrap ( mkWrapper )
41 import InstEnv ( DFunId )
42 import Id ( Id, mkVanillaGlobal, mkLocalId )
43 import MkId ( mkFCallId )
44 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
45 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
46 setArityInfo, setInlinePragInfo, setCafInfo,
47 vanillaIdInfo, newStrictnessInfo )
48 import Class ( Class )
49 import TyCon ( AlgTyConRhs(..), tyConDataCons, tyConTyVars, isTupleTyCon, mkForeignTyCon )
50 import DataCon ( dataConWorkId, dataConExistentialTyVars, dataConArgTys )
51 import TysWiredIn ( tupleCon )
52 import Var ( TyVar, mkTyVar, tyVarKind )
53 import Name ( Name, NamedThing(..), nameModuleName, nameModule, nameOccName,
54 isWiredInName, wiredInNameTyThing_maybe, nameParent, nameParent_maybe )
56 import OccName ( OccName )
57 import Module ( Module, ModuleName, moduleName )
58 import UniqSupply ( initUs_ )
60 import SrcLoc ( noSrcLoc )
61 import Util ( zipWithEqual, dropList, equalLength, zipLazy )
62 import Maybes ( expectJust )
63 import CmdLineOpts ( DynFlag(..), dopt )
72 An IfaceDecl is populated with RdrNames, and these are not renamed to
73 Names before typechecking, because there should be no scope errors etc.
75 -- For (b) consider: f = $(...h....)
76 -- where h is imported, and calls f via an hi-boot file.
77 -- This is bad! But it is not seen as a staging error, because h
78 -- is indeed imported. We don't want the type-checker to black-hole
79 -- when simplifying and compiling the splice!
81 -- Simple solution: discard any unfolding that mentions a variable
82 -- bound in this module (and hence not yet processed).
83 -- The discarding happens when forkM finds a type error.
85 %************************************************************************
87 %* tcImportDecl is the key function for "faulting in" *
90 %************************************************************************
92 The main idea is this. We are chugging along type-checking source code, and
93 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
94 it in the EPS type envt. So it
96 2 gets the decl for GHC.Base.map
97 3 typechecks it via tcIfaceDecl
98 4 and adds it to the type env in the EPS
100 Note that DURING STEP 4, we may find that map's type mentions a type
101 constructor that also
103 Notice that for imported things we read the current version from the EPS
104 mutable variable. This is important in situations like
106 where the code that e1 expands to might import some defns that
107 also turn out to be needed by the code that e2 expands to.
110 tcImportDecl :: Name -> IfG TyThing
111 -- Get the TyThing for this Name from an interface file
114 -- Make sure the interface is loaded
115 ; let { nd_doc = ptext SLIT("Need decl for") <+> ppr name }
116 ; traceIf (nd_doc <+> char '{') -- Brace matches the later message
117 ; loadHomeInterface nd_doc name
119 -- Get the real name of the thing, with a correct nameParent field.
120 -- Before the interface is loaded, we may have a non-committal 'Nothing'
121 -- in the namePareent field (made up by IfaceEnv.lookupOrig), but
122 -- loading the interface updates the name cache.
123 -- We need the right nameParent field in getThing
124 ; real_name <- lookupOrig (nameModuleName name) (nameOccName name)
126 -- Get the decl out of the EPS
127 ; main_thing <- ASSERT( real_name == name ) -- Unique should not change!
130 -- Record the import in the type env,
131 -- slurp any rules it allows in
132 ; recordImportOf main_thing
134 ; let { extra | getName main_thing == real_name = empty
135 | otherwise = brackets (ptext SLIT("when seeking") <+> ppr real_name) }
136 ; traceIf (ptext SLIT(" ...imported decl for") <+> ppr main_thing <+> extra <+> char '}')
139 -- Look up the wanted Name in the type envt; it might be
140 -- one of the subordinate members of the input thing
141 ; if real_name == getName main_thing
142 then return main_thing
145 ; return (expectJust "tcImportDecl" $
146 lookupTypeEnv (eps_PTE eps) real_name) }}
148 recordImportOf :: TyThing -> IfG ()
149 -- Update the EPS to record the import of the Thing
150 -- (a) augment the type environment; this is done even for wired-in
151 -- things, so that we don't go through this rigmarole a second time
152 -- (b) slurp in any rules to maintain the invariant that any rule
153 -- whose gates are all in the type envt, is in eps_rule_base
156 = do { new_things <- updateEps (\ eps ->
157 let { new_things = thing : implicitTyThings thing
158 ; new_type_env = extendTypeEnvList (eps_PTE eps) new_things
159 -- NB: opportunity for a very subtle loop here!
160 -- If working out what the implicitTyThings are involves poking
161 -- any of the fork'd thunks in 'thing', then here's what happens
162 -- * recordImportOf succeed, extending type-env with a thunk
163 -- * the next guy to pull on type-env forces the thunk
164 -- * which pokes the suspended forks
165 -- * which, to execute, need to consult type-env (to check
166 -- entirely unrelated types, perhaps)
168 in (eps { eps_PTE = new_type_env }, new_things)
170 ; traceIf (text "tcImport: extend type env" <+> ppr new_things)
173 getThing :: Name -> IfG TyThing
174 -- Find and typecheck the thing; the Name might be a "subordinate name"
175 -- of the "main thing" (e.g. the constructor of a data type declaration)
176 -- The Thing we return is the parent "main thing"
179 | Just thing <- wiredInNameTyThing_maybe name
182 | otherwise = do -- The normal case, not wired in
183 { -- Get the decl from the pool
184 mb_decl <- updateEps (\ eps -> selectDecl eps name)
187 Just decl -> initIfaceLcl (nameModuleName name) (tcIfaceDecl decl)
189 -- Side-effects EPS by faulting in any needed decls
190 -- (via nested calls to tcImportDecl)
193 Nothing -> do { ioToIOEnv (printErrs (msg defaultErrStyle)); failM }
194 -- Declaration not found
195 -- No errors-var to accumulate errors in, so just
196 -- print out the error right now
200 msg = hang (ptext SLIT("Can't find interface-file declaration for") <+> ppr (nameParent name))
201 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
202 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
204 selectDecl :: ExternalPackageState -> Name -> (ExternalPackageState, Maybe IfaceDecl)
205 -- Use nameParent to get the parent name of the thing
206 selectDecl eps@(EPS { eps_decls = Pool decls_map n_in n_out}) name
207 = case lookupNameEnv decls_map name of {
208 -- This first lookup will usually fail for subordinate names, because
209 -- the relevant decl is the parent decl.
210 -- But, if we export a data type decl abstractly, its selectors
211 -- get separate type signatures in the interface file
213 decls' = delFromNameEnv decls_map name
215 (eps {eps_decls = Pool decls' n_in (n_out+1)}, Just decl) ;
218 case nameParent_maybe name of {
219 Nothing -> (eps, Nothing ) ; -- No "parent"
220 Just main_name -> -- Has a parent; try that
222 case lookupNameEnv decls_map main_name of {
224 decls' = delFromNameEnv decls_map main_name
226 (eps {eps_decls = Pool decls' n_in (n_out+1)}, Just decl) ;
227 Nothing -> (eps, Nothing)
231 %************************************************************************
233 Type-checking a complete interface
235 %************************************************************************
237 Suppose we discover we don't need to recompile. Then we must type
238 check the old interface file. This is a bit different to the
239 incremental type checking we do as we suck in interface files. Instead
240 we do things similarly as when we are typechecking source decls: we
241 bring into scope the type envt for the interface all at once, using a
242 knot. Remember, the decls aren't necessarily in dependency order --
243 and even if they were, the type decls might be mutually recursive.
246 typecheckIface :: HscEnv
247 -> ModIface -- Get the decls from here
249 typecheckIface hsc_env iface@(ModIface { mi_module = mod, mi_decls = ver_decls,
250 mi_rules = rules, mi_insts = dfuns })
251 = initIfaceTc hsc_env iface $ \ tc_env_var -> do
252 { -- Typecheck the decls
253 names <- mappM (lookupOrig (moduleName mod) . ifName) decls
254 ; ty_things <- fixM (\ rec_ty_things -> do
255 { writeMutVar tc_env_var (mkNameEnv (names `zipLazy` rec_ty_things))
256 -- This only makes available the "main" things,
257 -- but that's enough for the strictly-checked part
258 ; mapM tcIfaceDecl decls })
260 -- Now augment the type envt with all the implicit things
261 -- These will be needed when type-checking the unfoldings for
262 -- the IfaceIds, but this is done lazily, so writing the thing
264 ; let { add_implicits main_thing = main_thing : implicitTyThings main_thing
265 ; type_env = mkTypeEnv (concatMap add_implicits ty_things) }
266 ; writeMutVar tc_env_var type_env
268 -- Now do those rules and instances
269 ; dfuns <- mapM tcIfaceInst (mi_insts iface)
270 ; rules <- mapM tcIfaceRule (mi_rules iface)
273 ; return (ModDetails { md_types = type_env, md_insts = dfuns, md_rules = rules })
276 decls = map snd ver_decls
280 %************************************************************************
282 Type and class declarations
284 %************************************************************************
286 When typechecking a data type decl, we *lazily* (via forkM) typecheck
287 the constructor argument types. This is in the hope that we may never
288 poke on those argument types, and hence may never need to load the
289 interface files for types mentioned in the arg types.
292 data Foo.S = MkS Baz.T
293 Mabye we can get away without even loading the interface for Baz!
295 This is not just a performance thing. Suppose we have
296 data Foo.S = MkS Baz.T
297 data Baz.T = MkT Foo.S
298 (in different interface files, of course).
299 Now, first we load and typecheck Foo.S, and add it to the type envt.
300 If we do explore MkS's argument, we'll load and typecheck Baz.T.
301 If we explore MkT's argument we'll find Foo.S already in the envt.
303 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
304 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
305 which isn't done yet.
307 All very cunning. However, there is a rather subtle gotcha which bit
308 me when developing this stuff. When we typecheck the decl for S, we
309 extend the type envt with S, MkS, and all its implicit Ids. Suppose
310 (a bug, but it happened) that the list of implicit Ids depended in
311 turn on the constructor arg types. Then the following sequence of
313 * we build a thunk <t> for the constructor arg tys
314 * we build a thunk for the extended type environment (depends on <t>)
315 * we write the extended type envt into the global EPS mutvar
317 Now we look something up in the type envt
319 * which reads the global type envt out of the global EPS mutvar
320 * but that depends in turn on <t>
322 It's subtle, because, it'd work fine if we typechecked the constructor args
323 eagerly -- they don't need the extended type envt. They just get the extended
324 type envt by accident, because they look at it later.
326 What this means is that the implicitTyThings MUST NOT DEPEND on any of
331 tcIfaceDecl :: IfaceDecl -> IfL TyThing
333 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
334 = do { name <- lookupIfaceTop occ_name
335 ; ty <- tcIfaceType iface_type
336 ; info <- tcIdInfo name ty info
337 ; return (AnId (mkVanillaGlobal name ty info)) }
339 tcIfaceDecl (IfaceData {ifName = occ_name,
340 ifTyVars = tv_bndrs, ifCtxt = rdr_ctxt,
342 ifVrcs = arg_vrcs, ifRec = is_rec,
343 ifGeneric = want_generic })
344 = do { tc_name <- lookupIfaceTop occ_name
345 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
347 { traceIf (text "tcIfaceDecl" <+> ppr rdr_ctxt)
349 ; ctxt <- forkM (ptext SLIT("Ctxt of data decl") <+> ppr tc_name) $
351 -- The reason for laziness here is to postpone
352 -- looking at the context, because the class may not
353 -- be in the type envt yet. E.g.
354 -- class Real a where { toRat :: a -> Ratio Integer }
355 -- data (Real a) => Ratio a = ...
356 -- We suck in the decl for Real, and type check it, which sucks
357 -- in the data type Ratio; but we must postpone typechecking the
360 ; tycon <- fixM ( \ tycon -> do
361 { cons <- tcIfaceDataCons tycon tyvars ctxt rdr_cons
362 ; tycon <- buildAlgTyCon tc_name tyvars ctxt cons
363 arg_vrcs is_rec want_generic
366 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
367 ; return (ATyCon tycon)
370 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
371 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
372 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
373 { tc_name <- lookupIfaceTop occ_name
374 ; rhs_ty <- tcIfaceType rdr_rhs_ty
375 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
378 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
379 ifFDs = rdr_fds, ifSigs = rdr_sigs,
380 ifVrcs = tc_vrcs, ifRec = tc_isrec })
381 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
382 { cls_name <- lookupIfaceTop occ_name
383 ; ctxt <- tcIfaceCtxt rdr_ctxt
384 ; sigs <- mappM tc_sig rdr_sigs
385 ; fds <- mappM tc_fd rdr_fds
386 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
387 ; return (AClass cls) }
389 tc_sig (IfaceClassOp occ dm rdr_ty)
390 = do { op_name <- lookupIfaceTop occ
391 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
392 -- Must be done lazily for just the same reason as the
393 -- context of a data decl: the type sig might mention the
394 -- class being defined
395 ; return (op_name, dm, op_ty) }
397 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
399 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
400 ; tvs2' <- mappM tcIfaceTyVar tvs2
401 ; return (tvs1', tvs2') }
403 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
404 = do { name <- lookupIfaceTop rdr_name
405 ; return (ATyCon (mkForeignTyCon name ext_name
406 liftedTypeKind 0 [])) }
408 tcIfaceDataCons tycon tyvars ctxt if_cons
410 IfAbstractTyCon -> return mkAbstractTyConRhs
411 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
412 ; return (mkDataTyConRhs data_cons) }
413 IfNewTyCon con -> do { data_con <- tc_con_decl con
414 ; return (mkNewTyConRhs data_con) }
416 tc_con_decl (IfaceConDecl occ ex_tvs ex_ctxt args stricts field_lbls)
417 = bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
418 { name <- lookupIfaceTop occ
419 ; ex_theta <- tcIfaceCtxt ex_ctxt -- Laziness seems not worth the bother here
421 -- Read the argument types, but lazily to avoid faulting in
422 -- the component types unless they are really needed
423 ; arg_tys <- forkM (mk_doc name args) (mappM tcIfaceType args) ;
425 ; lbl_names <- mappM lookupIfaceTop field_lbls
427 ; buildDataCon name stricts lbl_names
428 tyvars ctxt ex_tyvars ex_theta
431 mk_doc con_name args = ptext SLIT("Constructor") <+> sep [ppr con_name, ppr args]
435 %************************************************************************
439 %************************************************************************
441 The gating story for instance declarations
442 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
443 When we are looking for a dict (C t1..tn), we slurp in instance decls for
445 mention at least one of the type constructors
446 at the roots of t1..tn
448 Why "at least one" rather than "all"? Because functional dependencies
449 complicate the picture. Consider
450 class C a b | a->b where ...
451 instance C Foo Baz where ...
452 Here, the gates are really only C and Foo, *not* Baz.
453 That is, if C and Foo are visible, even if Baz isn't, we must
454 slurp the decl, even if Baz is thus far completely unknown to the
457 Why "roots of the types"? Reason is overlap. For example, suppose there
458 are interfaces in the pool for
462 Then, if we are trying to resolve (C Int x), we need (a)
463 if we are trying to resolve (C x [y]), we need *both* (b) and (c),
464 even though T is not involved yet, so that we spot the overlap.
467 NOTE: if you use an instance decl with NO type constructors
468 instance C a where ...
469 and look up an Inst that only has type variables such as (C (n o))
470 then GHC won't necessarily suck in the instances that overlap with this.
474 loadImportedInsts :: Class -> [Type] -> TcM PackageInstEnv
475 loadImportedInsts cls tys
476 = do { -- Get interfaces for wired-in things, such as Integer
477 -- Any non-wired-in tycons will already be loaded, else
478 -- we couldn't have them in the Type
479 ; this_mod <- getModule
480 ; let { (cls_gate, tc_gates) = predInstGates cls tys
481 ; imp_wi n = isWiredInName n && this_mod /= nameModule n
482 ; wired_tcs = filter imp_wi tc_gates }
483 -- Wired-in tycons not from this module. The "this-module"
484 -- test bites only when compiling Base etc, because loadHomeInterface
485 -- barfs if it's asked to load a non-existent interface
486 ; if null wired_tcs then returnM ()
487 else initIfaceTcRn (mapM_ (loadHomeInterface wired_doc) wired_tcs)
489 ; eps_var <- getEpsVar
490 ; eps <- readMutVar eps_var
492 -- For interest: report the no-type-constructor case.
493 -- Don't report when -fallow-undecidable-instances is on, because then
494 -- we call loadImportedInsts when looking up even predicates like (C a)
495 -- But without undecidable instances it's rare to see C (a b) and
496 -- somethat interesting
497 {- (comment out; happens a lot in some code)
500 ; WARN( not (dopt Opt_AllowUndecidableInstances dflags) && null tc_gates,
501 ptext SLIT("Interesting! No tycons in Inst:")
502 <+> pprClassPred cls tys )
506 -- Suck in the instances
507 ; let { (inst_pool', iface_insts)
508 = selectInsts (eps_insts eps) cls_gate tc_gates }
510 -- Empty => finish up rapidly, without writing to eps
511 ; if null iface_insts then
512 return (eps_inst_env eps)
514 { writeMutVar eps_var (eps {eps_insts = inst_pool'})
516 ; traceIf (sep [ptext SLIT("Importing instances for") <+> pprClassPred cls tys,
517 nest 2 (vcat (map ppr iface_insts))])
519 -- Typecheck the new instances
520 ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
522 -- And put them in the package instance environment
523 ; updateEps ( \ eps ->
525 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
527 (eps { eps_inst_env = inst_env' }, inst_env')
530 wired_doc = ptext SLIT("Need home inteface for wired-in thing")
532 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
534 tcIfaceInst :: IfaceInst -> IfL DFunId
535 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
536 = tcIfaceExtId (LocalTop dfun_occ)
538 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
539 selectInsts pool@(Pool insts n_in n_out) cls tycons
540 = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
542 (insts', iface_insts)
543 = case lookupNameEnv insts cls of {
544 Nothing -> (insts, []) ;
547 case choose1 gated_insts of {
548 (_, []) -> (insts, []) ; -- None picked
549 (gated_insts', iface_insts') ->
551 (extendNameEnv insts cls gated_insts', iface_insts') }}
554 | null tycons -- Bizarre special case of C (a b); then there are no tycons
555 = ([], map snd gated_insts) -- Just grab all the instances, no real alternative
556 | otherwise -- Normal case
557 = foldl choose2 ([],[]) gated_insts
559 -- Reverses the gated decls, but that doesn't matter
560 choose2 (gis, decls) (gates, decl)
561 | null gates -- Happens when we have 'instance T a where ...'
562 || any (`elem` tycons) gates = (gis, decl:decls)
563 | otherwise = ((gates,decl) : gis, decls)
566 %************************************************************************
570 %************************************************************************
572 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
573 are in the type environment. However, remember that typechecking a Rule may
574 (as a side effect) augment the type envt, and so we may need to iterate the process.
577 loadImportedRules :: HscEnv -> ModGuts -> IO PackageRuleBase
578 loadImportedRules hsc_env guts
579 = initIfaceRules hsc_env guts $ do
581 if_rules <- updateEps (\ eps ->
582 let { (new_pool, if_rules) = selectRules (eps_rules eps) (eps_PTE eps) }
583 in (eps { eps_rules = new_pool }, if_rules) )
585 ; traceIf (ptext SLIT("Importing rules:") <+> vcat (map ppr if_rules))
587 ; let tc_rule (mod, rule) = initIfaceLcl mod (tcIfaceRule rule)
588 ; core_rules <- mapM tc_rule if_rules
591 ; traceIf (ptext SLIT("Imported rules:") <+> pprIdRules core_rules)
593 -- Update the rule base and return it
594 ; updateEps (\ eps ->
595 let { new_rule_base = extendRuleBaseList (eps_rule_base eps) core_rules }
596 in (eps { eps_rule_base = new_rule_base }, new_rule_base)
599 -- Strictly speaking, at this point we should go round again, since
600 -- typechecking one set of rules may bring in new things which enable
601 -- some more rules to come in. But we call loadImportedRules several
602 -- times anyway, so I'm going to be lazy and ignore this.
606 selectRules :: RulePool -> TypeEnv -> (RulePool, [(ModuleName, IfaceRule)])
607 -- Not terribly efficient. Look at each rule in the pool to see if
608 -- all its gates are in the type env. If so, take it out of the pool.
609 -- If not, trim its gates for next time.
610 selectRules (Pool rules n_in n_out) type_env
611 = (Pool rules' n_in (n_out + length if_rules), if_rules)
613 (rules', if_rules) = foldl do_one ([], []) rules
615 do_one (pool, if_rules) (gates, rule)
616 | null gates' = (pool, rule:if_rules)
617 | otherwise = ((gates',rule) : pool, if_rules)
619 gates' = filter (not . (`elemNameEnv` type_env)) gates
622 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
623 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
624 ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
625 = bindIfaceBndrs bndrs $ \ bndrs' ->
626 do { fn <- tcIfaceExtId fn_rdr
627 ; args' <- mappM tcIfaceExpr args
628 ; rhs' <- tcIfaceExpr rhs
629 ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
631 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
632 = do { fn <- tcIfaceExtId fn_rdr
633 ; returnM (fn, core_rule) }
637 %************************************************************************
641 %************************************************************************
644 tcIfaceType :: IfaceType -> IfL Type
645 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
646 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
647 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
648 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
649 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
650 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
652 tcIfaceTypes tys = mapM tcIfaceType tys
654 -----------------------------------------
655 tcIfacePredType :: IfacePredType -> IfL PredType
656 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
657 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
659 -----------------------------------------
660 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
661 tcIfaceCtxt sts = mappM tcIfacePredType sts
665 %************************************************************************
669 %************************************************************************
672 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
673 tcIfaceExpr (IfaceType ty)
674 = tcIfaceType ty `thenM` \ ty' ->
677 tcIfaceExpr (IfaceLcl name)
678 = tcIfaceLclId name `thenM` \ id ->
681 tcIfaceExpr (IfaceExt gbl)
682 = tcIfaceExtId gbl `thenM` \ id ->
685 tcIfaceExpr (IfaceLit lit)
688 tcIfaceExpr (IfaceFCall cc ty)
689 = tcIfaceType ty `thenM` \ ty' ->
690 newUnique `thenM` \ u ->
691 returnM (Var (mkFCallId u cc ty'))
693 tcIfaceExpr (IfaceTuple boxity args)
694 = mappM tcIfaceExpr args `thenM` \ args' ->
696 -- Put the missing type arguments back in
697 con_args = map (Type . exprType) args' ++ args'
699 returnM (mkApps (Var con_id) con_args)
702 con_id = dataConWorkId (tupleCon boxity arity)
705 tcIfaceExpr (IfaceLam bndr body)
706 = bindIfaceBndr bndr $ \ bndr' ->
707 tcIfaceExpr body `thenM` \ body' ->
708 returnM (Lam bndr' body')
710 tcIfaceExpr (IfaceApp fun arg)
711 = tcIfaceExpr fun `thenM` \ fun' ->
712 tcIfaceExpr arg `thenM` \ arg' ->
713 returnM (App fun' arg')
715 tcIfaceExpr (IfaceCase scrut case_bndr alts)
716 = tcIfaceExpr scrut `thenM` \ scrut' ->
717 newIfaceName case_bndr `thenM` \ case_bndr_name ->
719 scrut_ty = exprType scrut'
720 case_bndr' = mkLocalId case_bndr_name scrut_ty
721 tc_app = splitTyConApp scrut_ty
722 -- NB: Won't always succeed (polymoprhic case)
723 -- but won't be demanded in those cases
724 -- NB: not tcSplitTyConApp; we are looking at Core here
725 -- look through non-rec newtypes to find the tycon that
726 -- corresponds to the datacon in this case alternative
728 extendIfaceIdEnv [case_bndr'] $
729 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
730 returnM (Case scrut' case_bndr' alts')
732 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
733 = tcIfaceExpr rhs `thenM` \ rhs' ->
734 bindIfaceId bndr $ \ bndr' ->
735 tcIfaceExpr body `thenM` \ body' ->
736 returnM (Let (NonRec bndr' rhs') body')
738 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
739 = bindIfaceIds bndrs $ \ bndrs' ->
740 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
741 tcIfaceExpr body `thenM` \ body' ->
742 returnM (Let (Rec (bndrs' `zip` rhss')) body')
744 (bndrs, rhss) = unzip pairs
746 tcIfaceExpr (IfaceNote note expr)
747 = tcIfaceExpr expr `thenM` \ expr' ->
749 IfaceCoerce to_ty -> tcIfaceType to_ty `thenM` \ to_ty' ->
750 returnM (Note (Coerce to_ty'
751 (exprType expr')) expr')
752 IfaceInlineCall -> returnM (Note InlineCall expr')
753 IfaceInlineMe -> returnM (Note InlineMe expr')
754 IfaceSCC cc -> returnM (Note (SCC cc) expr')
755 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
757 -------------------------
758 tcIfaceAlt _ (IfaceDefault, names, rhs)
759 = ASSERT( null names )
760 tcIfaceExpr rhs `thenM` \ rhs' ->
761 returnM (DEFAULT, [], rhs')
763 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
764 = ASSERT( null names )
765 tcIfaceExpr rhs `thenM` \ rhs' ->
766 returnM (LitAlt lit, [], rhs')
768 -- A case alternative is made quite a bit more complicated
769 -- by the fact that we omit type annotations because we can
770 -- work them out. True enough, but its not that easy!
771 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
773 tycon_mod = nameModuleName (tyConName tycon)
775 tcIfaceDataCon (ExtPkg tycon_mod data_occ) `thenM` \ con ->
776 newIfaceNames arg_occs `thenM` \ arg_names ->
778 ex_tyvars = dataConExistentialTyVars con
779 main_tyvars = tyConTyVars tycon
780 ex_tyvars' = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars]
781 ex_tys' = mkTyVarTys ex_tyvars'
782 arg_tys = dataConArgTys con (inst_tys ++ ex_tys')
783 id_names = dropList ex_tyvars arg_names
786 | not (equalLength id_names arg_tys)
787 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
788 (ppr main_tyvars <+> ppr ex_tyvars) $$
792 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
794 ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
795 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$ ppr main_tyvars )
796 extendIfaceTyVarEnv ex_tyvars' $
797 extendIfaceIdEnv arg_ids $
798 tcIfaceExpr rhs `thenM` \ rhs' ->
799 returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
801 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
802 = newIfaceNames arg_occs `thenM` \ arg_names ->
804 [con] = tyConDataCons tycon
805 arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
807 ASSERT( isTupleTyCon tycon )
808 extendIfaceIdEnv arg_ids $
809 tcIfaceExpr rhs `thenM` \ rhs' ->
810 returnM (DataAlt con, arg_ids, rhs')
815 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
816 tcExtCoreBindings mod [] = return []
817 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
819 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
820 do_one mod (IfaceNonRec bndr rhs) thing_inside
821 = do { rhs' <- tcIfaceExpr rhs
822 ; bndr' <- newExtCoreBndr mod bndr
823 ; extendIfaceIdEnv [bndr'] $ do
824 { core_binds <- thing_inside
825 ; return (NonRec bndr' rhs' : core_binds) }}
827 do_one mod (IfaceRec pairs) thing_inside
828 = do { bndrs' <- mappM (newExtCoreBndr mod) bndrs
829 ; extendIfaceIdEnv bndrs' $ do
830 { rhss' <- mappM tcIfaceExpr rhss
831 ; core_binds <- thing_inside
832 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
834 (bndrs,rhss) = unzip pairs
838 %************************************************************************
842 %************************************************************************
845 tcIdInfo name ty NoInfo = return vanillaIdInfo
846 tcIdInfo name ty DiscardedInfo = return vanillaIdInfo
847 tcIdInfo name ty (HasInfo iface_info)
848 = foldlM tcPrag init_info iface_info
850 -- Set the CgInfo to something sensible but uninformative before
851 -- we start; default assumption is that it has CAFs
852 init_info = vanillaIdInfo
854 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
855 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
856 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
858 -- The next two are lazy, so they don't transitively suck stuff in
859 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
860 tcPrag info (HsUnfold inline_prag expr)
861 = tcPragExpr name expr `thenM` \ maybe_expr' ->
863 -- maybe_expr' doesn't get looked at if the unfolding
864 -- is never inspected; so the typecheck doesn't even happen
865 unfold_info = case maybe_expr' of
866 Nothing -> noUnfolding
867 Just expr' -> mkTopUnfolding expr'
869 returnM (info `setUnfoldingInfoLazily` unfold_info
870 `setInlinePragInfo` inline_prag)
874 tcWorkerInfo ty info wkr_name arity
875 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
877 -- We return without testing maybe_wkr_id, but as soon as info is
878 -- looked at we will test it. That's ok, because its outside the
879 -- knot; and there seems no big reason to further defer the
880 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
881 -- over the unfolding until it's actually used does seem worth while.)
882 ; us <- newUniqueSupply
884 ; returnM (case mb_wkr_id of
886 Just wkr_id -> add_wkr_info us wkr_id info) }
888 doc = text "Worker for" <+> ppr wkr_name
889 add_wkr_info us wkr_id info
890 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
891 `setWorkerInfo` HasWorker wkr_id arity
893 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
895 -- We are relying here on strictness info always appearing
896 -- before worker info, fingers crossed ....
897 strict_sig = case newStrictnessInfo info of
899 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
902 For unfoldings we try to do the job lazily, so that we never type check
903 an unfolding that isn't going to be looked at.
906 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
909 tcIfaceExpr expr `thenM` \ core_expr' ->
911 -- Check for type consistency in the unfolding
912 ifOptM Opt_DoCoreLinting (
913 get_in_scope_ids `thenM` \ in_scope ->
914 case lintUnfolding noSrcLoc in_scope core_expr' of
915 Nothing -> returnM ()
916 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
921 doc = text "Unfolding of" <+> ppr name
922 get_in_scope_ids -- Urgh; but just for linting
924 do { env <- getGblEnv
925 ; case if_rec_types env of {
926 Nothing -> return [] ;
927 Just (_, get_env) -> do
928 { type_env <- get_env
929 ; return (typeEnvIds type_env) }}}
934 %************************************************************************
938 %************************************************************************
941 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
942 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
943 = bindIfaceId bndr thing_inside
944 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
945 = bindIfaceTyVar bndr thing_inside
947 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
948 bindIfaceBndrs [] thing_inside = thing_inside []
949 bindIfaceBndrs (b:bs) thing_inside
950 = bindIfaceBndr b $ \ b' ->
951 bindIfaceBndrs bs $ \ bs' ->
952 thing_inside (b':bs')
954 -----------------------
955 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
956 bindIfaceId (occ, ty) thing_inside
957 = do { name <- newIfaceName occ
958 ; ty' <- tcIfaceType ty
959 ; let { id = mkLocalId name ty' }
960 ; extendIfaceIdEnv [id] (thing_inside id) }
962 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
963 bindIfaceIds bndrs thing_inside
964 = do { names <- newIfaceNames occs
965 ; tys' <- mappM tcIfaceType tys
966 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
967 ; extendIfaceIdEnv ids (thing_inside ids) }
969 (occs,tys) = unzip bndrs
972 -----------------------
973 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
974 newExtCoreBndr mod (occ, ty)
975 = do { name <- newGlobalBinder mod occ Nothing noSrcLoc
976 ; ty' <- tcIfaceType ty
977 ; return (mkLocalId name ty') }
979 -----------------------
980 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
981 bindIfaceTyVar (occ,kind) thing_inside
982 = do { name <- newIfaceName occ
983 ; let tyvar = mk_iface_tyvar name kind
984 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
986 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
987 bindIfaceTyVars bndrs thing_inside
988 = do { names <- newIfaceNames occs
989 ; let tyvars = zipWith mk_iface_tyvar names kinds
990 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
992 (occs,kinds) = unzip bndrs
994 mk_iface_tyvar name kind = mkTyVar name kind