2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcIfaceSig]{Type checking of type signatures in interface files}
8 tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
9 tcIfaceDecl, tcIfaceInst, tcIfaceRules, tcIfaceGlobal,
13 #include "HsVersions.h"
16 import LoadIface ( loadInterface, loadWiredInHomeIface, findAndReadIface, loadDecls )
17 import IfaceEnv ( lookupIfaceTop, lookupIfaceExt, newGlobalBinder,
18 extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
19 tcIfaceTyVar, tcIfaceLclId, lookupIfaceTc,
20 newIfaceName, newIfaceNames, ifaceExportNames )
21 import BuildTyCl ( buildSynTyCon, buildAlgTyCon, buildDataCon,
23 mkAbstractTyConRhs, mkOpenDataTyConRhs,
24 mkOpenNewTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
26 import Type ( liftedTypeKind, splitTyConApp, mkTyConApp,
27 liftedTypeKindTyCon, unliftedTypeKindTyCon,
28 openTypeKindTyCon, argTypeKindTyCon,
29 ubxTupleKindTyCon, ThetaType )
30 import TypeRep ( Type(..), PredType(..) )
31 import TyCon ( TyCon, tyConName, SynTyConRhs(..), setTyConArgPoss )
32 import HscTypes ( ExternalPackageState(..),
33 TyThing(..), tyThingClass, tyThingTyCon,
34 ModIface(..), ModDetails(..), HomeModInfo(..),
35 emptyModDetails, lookupTypeEnv, lookupType,
36 typeEnvIds, mkDetailsFamInstCache )
37 import InstEnv ( Instance(..), mkImportedInstance )
39 import CoreUtils ( exprType, dataConRepFSInstPat )
41 import CoreLint ( lintUnfolding )
42 import WorkWrap ( mkWrapper )
43 import Id ( Id, mkVanillaGlobal, mkLocalId )
44 import MkId ( mkFCallId )
45 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
46 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
47 setArityInfo, setInlinePragInfo, setCafInfo,
48 vanillaIdInfo, newStrictnessInfo )
49 import Class ( Class )
50 import TyCon ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
51 import DataCon ( DataCon, dataConWorkId )
52 import TysWiredIn ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
53 import Var ( TyVar, mkTyVar )
54 import Name ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
55 nameOccName, wiredInNameTyThing_maybe )
57 import OccName ( OccName, mkVarOccFS, mkTyVarOcc, occNameSpace,
58 pprNameSpace, occNameFS )
59 import Module ( Module, moduleName )
60 import UniqFM ( lookupUFM )
61 import UniqSupply ( initUs_, uniqsFromSupply )
63 import ErrUtils ( Message )
64 import Maybes ( MaybeErr(..) )
65 import SrcLoc ( noSrcLoc )
66 import Util ( zipWithEqual )
67 import DynFlags ( DynFlag(..), isOneShot )
68 import Control.Monad ( unless )
70 import List ( elemIndex)
71 import Maybe ( catMaybes )
80 An IfaceDecl is populated with RdrNames, and these are not renamed to
81 Names before typechecking, because there should be no scope errors etc.
83 -- For (b) consider: f = $(...h....)
84 -- where h is imported, and calls f via an hi-boot file.
85 -- This is bad! But it is not seen as a staging error, because h
86 -- is indeed imported. We don't want the type-checker to black-hole
87 -- when simplifying and compiling the splice!
89 -- Simple solution: discard any unfolding that mentions a variable
90 -- bound in this module (and hence not yet processed).
91 -- The discarding happens when forkM finds a type error.
93 %************************************************************************
95 %* tcImportDecl is the key function for "faulting in" *
98 %************************************************************************
100 The main idea is this. We are chugging along type-checking source code, and
101 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
102 it in the EPS type envt. So it
104 2 gets the decl for GHC.Base.map
105 3 typechecks it via tcIfaceDecl
106 4 and adds it to the type env in the EPS
108 Note that DURING STEP 4, we may find that map's type mentions a type
109 constructor that also
111 Notice that for imported things we read the current version from the EPS
112 mutable variable. This is important in situations like
114 where the code that e1 expands to might import some defns that
115 also turn out to be needed by the code that e2 expands to.
118 tcImportDecl :: Name -> TcM TyThing
119 -- Entry point for *source-code* uses of importDecl
121 | Just thing <- wiredInNameTyThing_maybe name
122 = do { initIfaceTcRn (loadWiredInHomeIface name)
125 = do { traceIf (text "tcImportDecl" <+> ppr name)
126 ; mb_thing <- initIfaceTcRn (importDecl name)
128 Succeeded thing -> return thing
129 Failed err -> failWithTc err }
131 checkWiredInTyCon :: TyCon -> TcM ()
132 -- Ensure that the home module of the TyCon (and hence its instances)
133 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
134 -- in which case this is a no-op.
136 | not (isWiredInName tc_name)
139 = do { mod <- getModule
140 ; unless (mod == nameModule tc_name)
141 (initIfaceTcRn (loadWiredInHomeIface tc_name))
142 -- Don't look for (non-existent) Float.hi when
143 -- compiling Float.lhs, which mentions Float of course
144 -- A bit yukky to call initIfaceTcRn here
147 tc_name = tyConName tc
149 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
150 -- Get the TyThing for this Name from an interface file
151 -- It's not a wired-in thing -- the caller caught that
153 = ASSERT( not (isWiredInName name) )
156 -- Load the interface, which should populate the PTE
157 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
159 Failed err_msg -> return (Failed err_msg) ;
160 Succeeded iface -> do
162 -- Now look it up again; this time we should find it
164 ; case lookupTypeEnv (eps_PTE eps) name of
165 Just thing -> return (Succeeded thing)
166 Nothing -> return (Failed not_found_msg)
169 nd_doc = ptext SLIT("Need decl for") <+> ppr name
170 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
171 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
172 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
173 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
176 %************************************************************************
178 Type-checking a complete interface
180 %************************************************************************
182 Suppose we discover we don't need to recompile. Then we must type
183 check the old interface file. This is a bit different to the
184 incremental type checking we do as we suck in interface files. Instead
185 we do things similarly as when we are typechecking source decls: we
186 bring into scope the type envt for the interface all at once, using a
187 knot. Remember, the decls aren't necessarily in dependency order --
188 and even if they were, the type decls might be mutually recursive.
191 typecheckIface :: ModIface -- Get the decls from here
192 -> TcRnIf gbl lcl ModDetails
194 = initIfaceTc iface $ \ tc_env_var -> do
195 -- The tc_env_var is freshly allocated, private to
196 -- type-checking this particular interface
197 { -- Get the right set of decls and rules. If we are compiling without -O
198 -- we discard pragmas before typechecking, so that we don't "see"
199 -- information that we shouldn't. From a versioning point of view
200 -- It's not actually *wrong* to do so, but in fact GHCi is unable
201 -- to handle unboxed tuples, so it must not see unfoldings.
202 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
204 -- Typecheck the decls. This is done lazily, so that the knot-tying
205 -- within this single module work out right. In the If monad there is
206 -- no global envt for the current interface; instead, the knot is tied
207 -- through the if_rec_types field of IfGblEnv
208 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
209 ; let type_env = mkNameEnv names_w_things
210 ; writeMutVar tc_env_var type_env
212 -- Now do those rules and instances
213 ; dfuns <- mapM tcIfaceInst (mi_insts iface)
214 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
217 ; exports <- ifaceExportNames (mi_exports iface)
220 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
221 text "Type envt:" <+> ppr type_env])
222 ; return $ ModDetails { md_types = type_env
224 , md_fam_insts = mkDetailsFamInstCache type_env
226 , md_exports = exports
232 %************************************************************************
234 Type and class declarations
236 %************************************************************************
239 tcHiBootIface :: Module -> TcRn ModDetails
240 -- Load the hi-boot iface for the module being compiled,
241 -- if it indeed exists in the transitive closure of imports
242 -- Return the ModDetails, empty if no hi-boot iface
244 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
247 ; if not (isOneShot mode)
248 -- In --make and interactive mode, if this module has an hs-boot file
249 -- we'll have compiled it already, and it'll be in the HPT
251 -- We check wheher the interface is a *boot* interface.
252 -- It can happen (when using GHC from Visual Studio) that we
253 -- compile a module in TypecheckOnly mode, with a stable,
254 -- fully-populated HPT. In that case the boot interface isn't there
255 -- (it's been replaced by the mother module) so we can't check it.
256 -- And that's fine, because if M's ModInfo is in the HPT, then
257 -- it's been compiled once, and we don't need to check the boot iface
258 then do { hpt <- getHpt
259 ; case lookupUFM hpt (moduleName mod) of
260 Just info | mi_boot (hm_iface info)
261 -> return (hm_details info)
262 other -> return emptyModDetails }
265 -- OK, so we're in one-shot mode.
266 -- In that case, we're read all the direct imports by now,
267 -- so eps_is_boot will record if any of our imports mention us by
268 -- way of hi-boot file
270 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
271 Nothing -> return emptyModDetails ; -- The typical case
273 Just (_, False) -> failWithTc moduleLoop ;
274 -- Someone below us imported us!
275 -- This is a loop with no hi-boot in the way
277 Just (_mod, True) -> -- There's a hi-boot interface below us
279 do { read_result <- findAndReadIface
283 ; case read_result of
284 Failed err -> failWithTc (elaborate err)
285 Succeeded (iface, _path) -> typecheckIface iface
288 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
289 <+> ptext SLIT("to compare against the Real Thing")
291 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
292 <+> ptext SLIT("depends on itself")
294 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
295 quotes (ppr mod) <> colon) 4 err
299 %************************************************************************
301 Type and class declarations
303 %************************************************************************
305 When typechecking a data type decl, we *lazily* (via forkM) typecheck
306 the constructor argument types. This is in the hope that we may never
307 poke on those argument types, and hence may never need to load the
308 interface files for types mentioned in the arg types.
311 data Foo.S = MkS Baz.T
312 Mabye we can get away without even loading the interface for Baz!
314 This is not just a performance thing. Suppose we have
315 data Foo.S = MkS Baz.T
316 data Baz.T = MkT Foo.S
317 (in different interface files, of course).
318 Now, first we load and typecheck Foo.S, and add it to the type envt.
319 If we do explore MkS's argument, we'll load and typecheck Baz.T.
320 If we explore MkT's argument we'll find Foo.S already in the envt.
322 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
323 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
324 which isn't done yet.
326 All very cunning. However, there is a rather subtle gotcha which bit
327 me when developing this stuff. When we typecheck the decl for S, we
328 extend the type envt with S, MkS, and all its implicit Ids. Suppose
329 (a bug, but it happened) that the list of implicit Ids depended in
330 turn on the constructor arg types. Then the following sequence of
332 * we build a thunk <t> for the constructor arg tys
333 * we build a thunk for the extended type environment (depends on <t>)
334 * we write the extended type envt into the global EPS mutvar
336 Now we look something up in the type envt
338 * which reads the global type envt out of the global EPS mutvar
339 * but that depends in turn on <t>
341 It's subtle, because, it'd work fine if we typechecked the constructor args
342 eagerly -- they don't need the extended type envt. They just get the extended
343 type envt by accident, because they look at it later.
345 What this means is that the implicitTyThings MUST NOT DEPEND on any of
350 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
354 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
355 = do { name <- lookupIfaceTop occ_name
356 ; ty <- tcIfaceType iface_type
357 ; info <- tcIdInfo ignore_prags name ty info
358 ; return (AnId (mkVanillaGlobal name ty info)) }
360 tcIfaceDecl ignore_prags
361 (IfaceData {ifName = occ_name,
363 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
366 ifGeneric = want_generic,
367 ifFamInst = mb_family })
368 = do { tc_name <- lookupIfaceTop occ_name
369 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
371 { tycon <- fixM ( \ tycon -> do
372 { stupid_theta <- tcIfaceCtxt ctxt
375 Nothing -> return Nothing
376 Just (IfaceFamInst { ifFamInstTyCon = fam
379 do { famTyCon <- tcIfaceTyCon fam
380 ; insttys <- mapM tcIfaceType tys
381 ; return $ Just (famTyCon, insttys)
383 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
384 ; buildAlgTyCon tc_name tyvars stupid_theta
385 cons is_rec want_generic gadt_syn famInst
387 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
388 ; return (ATyCon tycon)
391 tcIfaceDecl ignore_prags
392 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
393 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
394 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
395 { tc_name <- lookupIfaceTop occ_name
396 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
397 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki
398 else SynonymTyCon rhs_tyki
399 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs))
402 tcIfaceDecl ignore_prags
403 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
404 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
405 ifATs = rdr_ats, ifSigs = rdr_sigs,
407 -- ToDo: in hs-boot files we should really treat abstract classes specially,
408 -- as we do abstract tycons
409 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
410 { cls_name <- lookupIfaceTop occ_name
411 ; ctxt <- tcIfaceCtxt rdr_ctxt
412 ; sigs <- mappM tc_sig rdr_sigs
413 ; fds <- mappM tc_fd rdr_fds
414 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
415 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
416 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
417 ; return (AClass cls) }
419 tc_sig (IfaceClassOp occ dm rdr_ty)
420 = do { op_name <- lookupIfaceTop occ
421 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
422 -- Must be done lazily for just the same reason as the
423 -- context of a data decl: the type sig might mention the
424 -- class being defined
425 ; return (op_name, dm, op_ty) }
427 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
429 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
430 ; tvs2' <- mappM tcIfaceTyVar tvs2
431 ; return (tvs1', tvs2') }
433 -- For each AT argument compute the position of the corresponding class
434 -- parameter in the class head. This will later serve as a permutation
435 -- vector when checking the validity of instance declarations.
436 setTyThingPoss (ATyCon tycon) atTyVars =
437 let classTyVars = map fst tv_bndrs
439 . map ((`elemIndex` classTyVars) . fst)
441 -- There will be no Nothing, as we already passed renaming
443 ATyCon (setTyConArgPoss tycon poss)
444 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
446 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
447 = do { name <- lookupIfaceTop rdr_name
448 ; return (ATyCon (mkForeignTyCon name ext_name
451 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
453 IfAbstractTyCon -> return mkAbstractTyConRhs
454 IfOpenDataTyCon -> return mkOpenDataTyConRhs
455 IfOpenNewTyCon -> return mkOpenNewTyConRhs
456 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
457 ; return (mkDataTyConRhs data_cons) }
458 IfNewTyCon con -> do { data_con <- tc_con_decl con
459 ; mkNewTyConRhs tycon_name tycon data_con }
461 tc_con_decl (IfCon { ifConInfix = is_infix,
462 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
463 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
464 ifConArgTys = args, ifConFields = field_lbls,
465 ifConStricts = stricts})
466 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
467 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
468 { name <- lookupIfaceTop occ
469 ; eq_spec <- tcIfaceEqSpec spec
470 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
471 -- At one stage I thought that this context checking *had*
472 -- to be lazy, because of possible mutual recursion between the
473 -- type and the classe:
475 -- class Real a where { toRat :: a -> Ratio Integer }
476 -- data (Real a) => Ratio a = ...
477 -- But now I think that the laziness in checking class ops breaks
478 -- the loop, so no laziness needed
480 -- Read the argument types, but lazily to avoid faulting in
481 -- the component types unless they are really needed
482 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
483 ; lbl_names <- mappM lookupIfaceTop field_lbls
485 ; buildDataCon name is_infix {- Not infix -}
487 univ_tyvars ex_tyvars
491 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
496 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
497 ; ty <- tcIfaceType if_ty
502 %************************************************************************
506 %************************************************************************
509 tcIfaceInst :: IfaceInst -> IfL Instance
510 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
511 ifInstCls = cls, ifInstTys = mb_tcs,
513 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
514 tcIfaceExtId (LocalTop dfun_occ)
515 ; cls' <- lookupIfaceExt cls
516 ; mb_tcs' <- mapM do_tc mb_tcs
517 ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
519 do_tc Nothing = return Nothing
520 do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
524 %************************************************************************
528 %************************************************************************
530 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
531 are in the type environment. However, remember that typechecking a Rule may
532 (as a side effect) augment the type envt, and so we may need to iterate the process.
535 tcIfaceRules :: Bool -- True <=> ignore rules
538 tcIfaceRules ignore_prags if_rules
539 | ignore_prags = return []
540 | otherwise = mapM tcIfaceRule if_rules
542 tcIfaceRule :: IfaceRule -> IfL CoreRule
543 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
544 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
546 = do { fn' <- lookupIfaceExt fn
547 ; ~(bndrs', args', rhs') <-
548 -- Typecheck the payload lazily, in the hope it'll never be looked at
549 forkM (ptext SLIT("Rule") <+> ftext name) $
550 bindIfaceBndrs bndrs $ \ bndrs' ->
551 do { args' <- mappM tcIfaceExpr args
552 ; rhs' <- tcIfaceExpr rhs
553 ; return (bndrs', args', rhs') }
554 ; mb_tcs <- mapM ifTopFreeName args
555 ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act,
556 ru_bndrs = bndrs', ru_args = args',
557 ru_rhs = rhs', ru_orph = orph,
559 ru_local = isLocalIfaceExtName fn }) }
561 -- This function *must* mirror exactly what Rules.topFreeName does
562 -- We could have stored the ru_rough field in the iface file
563 -- but that would be redundant, I think.
564 -- The only wrinkle is that we must not be deceived by
565 -- type syononyms at the top of a type arg. Since
566 -- we can't tell at this point, we are careful not
567 -- to write them out in coreRuleToIfaceRule
568 ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
569 ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
570 = do { n <- lookupIfaceTc tc
572 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
573 ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
575 ifTopFreeName other = return Nothing
579 %************************************************************************
583 %************************************************************************
586 tcIfaceType :: IfaceType -> IfL Type
587 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
588 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
589 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
590 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
591 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
592 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
594 tcIfaceTypes tys = mapM tcIfaceType tys
596 -----------------------------------------
597 tcIfacePredType :: IfacePredType -> IfL PredType
598 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
599 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
600 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
602 -----------------------------------------
603 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
604 tcIfaceCtxt sts = mappM tcIfacePredType sts
608 %************************************************************************
612 %************************************************************************
615 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
616 tcIfaceExpr (IfaceType ty)
617 = tcIfaceType ty `thenM` \ ty' ->
620 tcIfaceExpr (IfaceLcl name)
621 = tcIfaceLclId name `thenM` \ id ->
624 tcIfaceExpr (IfaceExt gbl)
625 = tcIfaceExtId gbl `thenM` \ id ->
628 tcIfaceExpr (IfaceLit lit)
631 tcIfaceExpr (IfaceFCall cc ty)
632 = tcIfaceType ty `thenM` \ ty' ->
633 newUnique `thenM` \ u ->
634 returnM (Var (mkFCallId u cc ty'))
636 tcIfaceExpr (IfaceTuple boxity args)
637 = mappM tcIfaceExpr args `thenM` \ args' ->
639 -- Put the missing type arguments back in
640 con_args = map (Type . exprType) args' ++ args'
642 returnM (mkApps (Var con_id) con_args)
645 con_id = dataConWorkId (tupleCon boxity arity)
648 tcIfaceExpr (IfaceLam bndr body)
649 = bindIfaceBndr bndr $ \ bndr' ->
650 tcIfaceExpr body `thenM` \ body' ->
651 returnM (Lam bndr' body')
653 tcIfaceExpr (IfaceApp fun arg)
654 = tcIfaceExpr fun `thenM` \ fun' ->
655 tcIfaceExpr arg `thenM` \ arg' ->
656 returnM (App fun' arg')
658 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
659 = tcIfaceExpr scrut `thenM` \ scrut' ->
660 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
662 scrut_ty = exprType scrut'
663 case_bndr' = mkLocalId case_bndr_name scrut_ty
664 tc_app = splitTyConApp scrut_ty
665 -- NB: Won't always succeed (polymoprhic case)
666 -- but won't be demanded in those cases
667 -- NB: not tcSplitTyConApp; we are looking at Core here
668 -- look through non-rec newtypes to find the tycon that
669 -- corresponds to the datacon in this case alternative
671 extendIfaceIdEnv [case_bndr'] $
672 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
673 tcIfaceType ty `thenM` \ ty' ->
674 returnM (Case scrut' case_bndr' ty' alts')
676 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
677 = tcIfaceExpr rhs `thenM` \ rhs' ->
678 bindIfaceId bndr $ \ bndr' ->
679 tcIfaceExpr body `thenM` \ body' ->
680 returnM (Let (NonRec bndr' rhs') body')
682 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
683 = bindIfaceIds bndrs $ \ bndrs' ->
684 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
685 tcIfaceExpr body `thenM` \ body' ->
686 returnM (Let (Rec (bndrs' `zip` rhss')) body')
688 (bndrs, rhss) = unzip pairs
690 tcIfaceExpr (IfaceCast expr co) = do
691 expr' <- tcIfaceExpr expr
692 co' <- tcIfaceType co
693 returnM (Cast expr' co')
695 tcIfaceExpr (IfaceNote note expr)
696 = tcIfaceExpr expr `thenM` \ expr' ->
698 IfaceInlineMe -> returnM (Note InlineMe expr')
699 IfaceSCC cc -> returnM (Note (SCC cc) expr')
700 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
702 -------------------------
703 tcIfaceAlt _ (IfaceDefault, names, rhs)
704 = ASSERT( null names )
705 tcIfaceExpr rhs `thenM` \ rhs' ->
706 returnM (DEFAULT, [], rhs')
708 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
709 = ASSERT( null names )
710 tcIfaceExpr rhs `thenM` \ rhs' ->
711 returnM (LitAlt lit, [], rhs')
713 -- A case alternative is made quite a bit more complicated
714 -- by the fact that we omit type annotations because we can
715 -- work them out. True enough, but its not that easy!
716 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
717 = do { let tycon_mod = nameModule (tyConName tycon)
718 ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
719 ; ASSERT2( con `elem` tyConDataCons tycon,
720 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
721 tcIfaceDataAlt con inst_tys arg_strs rhs }
723 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
724 = ASSERT( isTupleTyCon tycon )
725 do { let [data_con] = tyConDataCons tycon
726 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
728 tcIfaceDataAlt con inst_tys arg_strs rhs
729 = do { us <- newUniqueSupply
730 ; let uniqs = uniqsFromSupply us
731 ; let (ex_tvs, co_tvs, arg_ids)
732 = dataConRepFSInstPat arg_strs uniqs con inst_tys
733 all_tvs = ex_tvs ++ co_tvs
735 ; rhs' <- extendIfaceTyVarEnv all_tvs $
736 extendIfaceIdEnv arg_ids $
738 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
743 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
744 tcExtCoreBindings [] = return []
745 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
747 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
748 do_one (IfaceNonRec bndr rhs) thing_inside
749 = do { rhs' <- tcIfaceExpr rhs
750 ; bndr' <- newExtCoreBndr bndr
751 ; extendIfaceIdEnv [bndr'] $ do
752 { core_binds <- thing_inside
753 ; return (NonRec bndr' rhs' : core_binds) }}
755 do_one (IfaceRec pairs) thing_inside
756 = do { bndrs' <- mappM newExtCoreBndr bndrs
757 ; extendIfaceIdEnv bndrs' $ do
758 { rhss' <- mappM tcIfaceExpr rhss
759 ; core_binds <- thing_inside
760 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
762 (bndrs,rhss) = unzip pairs
766 %************************************************************************
770 %************************************************************************
773 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
774 tcIdInfo ignore_prags name ty info
775 | ignore_prags = return vanillaIdInfo
776 | otherwise = case info of
777 NoInfo -> return vanillaIdInfo
778 HasInfo info -> foldlM tcPrag init_info info
780 -- Set the CgInfo to something sensible but uninformative before
781 -- we start; default assumption is that it has CAFs
782 init_info = vanillaIdInfo
784 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
785 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
786 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
788 -- The next two are lazy, so they don't transitively suck stuff in
789 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
790 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
791 tcPrag info (HsUnfold expr)
792 = tcPragExpr name expr `thenM` \ maybe_expr' ->
794 -- maybe_expr' doesn't get looked at if the unfolding
795 -- is never inspected; so the typecheck doesn't even happen
796 unfold_info = case maybe_expr' of
797 Nothing -> noUnfolding
798 Just expr' -> mkTopUnfolding expr'
800 returnM (info `setUnfoldingInfoLazily` unfold_info)
804 tcWorkerInfo ty info wkr arity
805 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
807 -- We return without testing maybe_wkr_id, but as soon as info is
808 -- looked at we will test it. That's ok, because its outside the
809 -- knot; and there seems no big reason to further defer the
810 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
811 -- over the unfolding until it's actually used does seem worth while.)
812 ; us <- newUniqueSupply
814 ; returnM (case mb_wkr_id of
816 Just wkr_id -> add_wkr_info us wkr_id info) }
818 doc = text "Worker for" <+> ppr wkr
819 add_wkr_info us wkr_id info
820 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
821 `setWorkerInfo` HasWorker wkr_id arity
823 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
825 -- We are relying here on strictness info always appearing
826 -- before worker info, fingers crossed ....
827 strict_sig = case newStrictnessInfo info of
829 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
832 For unfoldings we try to do the job lazily, so that we never type check
833 an unfolding that isn't going to be looked at.
836 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
839 tcIfaceExpr expr `thenM` \ core_expr' ->
841 -- Check for type consistency in the unfolding
842 ifOptM Opt_DoCoreLinting (
843 get_in_scope_ids `thenM` \ in_scope ->
844 case lintUnfolding noSrcLoc in_scope core_expr' of
845 Nothing -> returnM ()
846 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
851 doc = text "Unfolding of" <+> ppr name
852 get_in_scope_ids -- Urgh; but just for linting
854 do { env <- getGblEnv
855 ; case if_rec_types env of {
856 Nothing -> return [] ;
857 Just (_, get_env) -> do
858 { type_env <- get_env
859 ; return (typeEnvIds type_env) }}}
864 %************************************************************************
866 Getting from Names to TyThings
868 %************************************************************************
871 tcIfaceGlobal :: Name -> IfL TyThing
873 | Just thing <- wiredInNameTyThing_maybe name
874 -- Wired-in things include TyCons, DataCons, and Ids
875 = do { ifCheckWiredInThing name; return thing }
877 = do { (eps,hpt) <- getEpsAndHpt
879 ; case lookupType dflags hpt (eps_PTE eps) name of {
880 Just thing -> return thing ;
884 ; case if_rec_types env of {
885 Just (mod, get_type_env)
886 | nameIsLocalOrFrom mod name
887 -> do -- It's defined in the module being compiled
888 { type_env <- setLclEnv () get_type_env -- yuk
889 ; case lookupNameEnv type_env name of
890 Just thing -> return thing
891 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
892 (ppr name $$ ppr type_env) }
896 { mb_thing <- importDecl name -- It's imported; go get it
898 Failed err -> failIfM err
899 Succeeded thing -> return thing
902 ifCheckWiredInThing :: Name -> IfL ()
903 -- Even though we are in an interface file, we want to make
904 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
905 -- Ditto want to ensure that RULES are loaded too
906 ifCheckWiredInThing name
907 = do { mod <- getIfModule
908 -- Check whether we are typechecking the interface for this
909 -- very module. E.g when compiling the base library in --make mode
910 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
911 -- the HPT, so without the test we'll demand-load it into the PIT!
912 -- C.f. the same test in checkWiredInTyCon above
913 ; unless (mod == nameModule name)
914 (loadWiredInHomeIface name) }
916 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
917 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
918 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
919 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
920 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
921 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
922 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
923 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
924 ; thing <- tcIfaceGlobal name
925 ; return (check_tc (tyThingTyCon thing)) }
928 check_tc tc = case toIfaceTyCon (error "urk") tc of
930 other -> pprTrace "check_tc" (ppr tc) tc
934 -- we should be okay just returning Kind constructors without extra loading
935 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
936 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
937 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
938 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
939 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
941 -- Even though we are in an interface file, we want to make
942 -- sure the instances and RULES of this tycon are loaded
943 -- Imagine: f :: Double -> Double
944 tcWiredInTyCon :: TyCon -> IfL TyCon
945 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
948 tcIfaceClass :: IfaceExtName -> IfL Class
949 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
950 ; thing <- tcIfaceGlobal name
951 ; return (tyThingClass thing) }
953 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
954 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
955 ; thing <- tcIfaceGlobal name
957 ADataCon dc -> return dc
958 other -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
960 tcIfaceExtId :: IfaceExtName -> IfL Id
961 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
962 ; thing <- tcIfaceGlobal name
965 other -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
968 %************************************************************************
972 %************************************************************************
975 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
976 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
977 = bindIfaceId bndr thing_inside
978 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
979 = bindIfaceTyVar bndr thing_inside
981 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
982 bindIfaceBndrs [] thing_inside = thing_inside []
983 bindIfaceBndrs (b:bs) thing_inside
984 = bindIfaceBndr b $ \ b' ->
985 bindIfaceBndrs bs $ \ bs' ->
986 thing_inside (b':bs')
988 -----------------------
989 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
990 bindIfaceId (occ, ty) thing_inside
991 = do { name <- newIfaceName (mkVarOccFS occ)
992 ; ty' <- tcIfaceType ty
993 ; let { id = mkLocalId name ty' }
994 ; extendIfaceIdEnv [id] (thing_inside id) }
996 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
997 bindIfaceIds bndrs thing_inside
998 = do { names <- newIfaceNames (map mkVarOccFS occs)
999 ; tys' <- mappM tcIfaceType tys
1000 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
1001 ; extendIfaceIdEnv ids (thing_inside ids) }
1003 (occs,tys) = unzip bndrs
1006 -----------------------
1007 newExtCoreBndr :: IfaceIdBndr -> IfL Id
1008 newExtCoreBndr (var, ty)
1009 = do { mod <- getIfModule
1010 ; name <- newGlobalBinder mod (mkVarOccFS var) Nothing noSrcLoc
1011 ; ty' <- tcIfaceType ty
1012 ; return (mkLocalId name ty') }
1014 -----------------------
1015 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1016 bindIfaceTyVar (occ,kind) thing_inside
1017 = do { name <- newIfaceName (mkTyVarOcc occ)
1018 ; tyvar <- mk_iface_tyvar name kind
1019 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1021 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1022 bindIfaceTyVars bndrs thing_inside
1023 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1024 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1025 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1027 (occs,kinds) = unzip bndrs
1029 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1030 mk_iface_tyvar name ifKind = do { kind <- tcIfaceType ifKind
1031 ; return (mkTyVar name kind)