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, tcIfaceFamInst, tcIfaceRules, tcIfaceGlobal,
13 #include "HsVersions.h"
16 import LoadIface ( loadInterface, loadWiredInHomeIface, findAndReadIface, loadDecls )
17 import IfaceEnv ( lookupIfaceTop, newGlobalBinder,
18 extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
19 tcIfaceTyVar, tcIfaceLclId,
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,
37 import InstEnv ( Instance(..), mkImportedInstance )
38 import FamInstEnv ( FamInst(..), mkImportedFamInst )
40 import CoreUtils ( exprType, dataConRepFSInstPat )
42 import CoreLint ( lintUnfolding )
43 import WorkWrap ( mkWrapper )
44 import Id ( Id, mkVanillaGlobal, mkLocalId )
45 import MkId ( mkFCallId )
46 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
47 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
48 setArityInfo, setInlinePragInfo, setCafInfo,
49 vanillaIdInfo, newStrictnessInfo )
50 import Class ( Class )
51 import TyCon ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
52 import DataCon ( DataCon, dataConWorkId )
53 import TysWiredIn ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
54 import Var ( TyVar, mkTyVar )
55 import Name ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
56 nameOccName, wiredInNameTyThing_maybe )
58 import OccName ( OccName, mkVarOccFS, mkTyVarOcc, occNameSpace,
59 pprNameSpace, occNameFS )
60 import Module ( Module, moduleName )
61 import UniqFM ( lookupUFM )
62 import UniqSupply ( initUs_, uniqsFromSupply )
64 import ErrUtils ( Message )
65 import Maybes ( MaybeErr(..) )
66 import SrcLoc ( noSrcLoc )
67 import Util ( zipWithEqual )
68 import DynFlags ( DynFlag(..), isOneShot )
69 import Control.Monad ( unless )
71 import List ( elemIndex)
72 import Maybe ( catMaybes )
81 An IfaceDecl is populated with RdrNames, and these are not renamed to
82 Names before typechecking, because there should be no scope errors etc.
84 -- For (b) consider: f = $(...h....)
85 -- where h is imported, and calls f via an hi-boot file.
86 -- This is bad! But it is not seen as a staging error, because h
87 -- is indeed imported. We don't want the type-checker to black-hole
88 -- when simplifying and compiling the splice!
90 -- Simple solution: discard any unfolding that mentions a variable
91 -- bound in this module (and hence not yet processed).
92 -- The discarding happens when forkM finds a type error.
94 %************************************************************************
96 %* tcImportDecl is the key function for "faulting in" *
99 %************************************************************************
101 The main idea is this. We are chugging along type-checking source code, and
102 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
103 it in the EPS type envt. So it
105 2 gets the decl for GHC.Base.map
106 3 typechecks it via tcIfaceDecl
107 4 and adds it to the type env in the EPS
109 Note that DURING STEP 4, we may find that map's type mentions a type
110 constructor that also
112 Notice that for imported things we read the current version from the EPS
113 mutable variable. This is important in situations like
115 where the code that e1 expands to might import some defns that
116 also turn out to be needed by the code that e2 expands to.
119 tcImportDecl :: Name -> TcM TyThing
120 -- Entry point for *source-code* uses of importDecl
122 | Just thing <- wiredInNameTyThing_maybe name
123 = do { initIfaceTcRn (loadWiredInHomeIface name)
126 = do { traceIf (text "tcImportDecl" <+> ppr name)
127 ; mb_thing <- initIfaceTcRn (importDecl name)
129 Succeeded thing -> return thing
130 Failed err -> failWithTc err }
132 checkWiredInTyCon :: TyCon -> TcM ()
133 -- Ensure that the home module of the TyCon (and hence its instances)
134 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
135 -- in which case this is a no-op.
137 | not (isWiredInName tc_name)
140 = do { mod <- getModule
141 ; unless (mod == nameModule tc_name)
142 (initIfaceTcRn (loadWiredInHomeIface tc_name))
143 -- Don't look for (non-existent) Float.hi when
144 -- compiling Float.lhs, which mentions Float of course
145 -- A bit yukky to call initIfaceTcRn here
148 tc_name = tyConName tc
150 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
151 -- Get the TyThing for this Name from an interface file
152 -- It's not a wired-in thing -- the caller caught that
154 = ASSERT( not (isWiredInName name) )
157 -- Load the interface, which should populate the PTE
158 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
160 Failed err_msg -> return (Failed err_msg) ;
161 Succeeded iface -> do
163 -- Now look it up again; this time we should find it
165 ; case lookupTypeEnv (eps_PTE eps) name of
166 Just thing -> return (Succeeded thing)
167 Nothing -> return (Failed not_found_msg)
170 nd_doc = ptext SLIT("Need decl for") <+> ppr name
171 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
172 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
173 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
174 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
177 %************************************************************************
179 Type-checking a complete interface
181 %************************************************************************
183 Suppose we discover we don't need to recompile. Then we must type
184 check the old interface file. This is a bit different to the
185 incremental type checking we do as we suck in interface files. Instead
186 we do things similarly as when we are typechecking source decls: we
187 bring into scope the type envt for the interface all at once, using a
188 knot. Remember, the decls aren't necessarily in dependency order --
189 and even if they were, the type decls might be mutually recursive.
192 typecheckIface :: ModIface -- Get the decls from here
193 -> TcRnIf gbl lcl ModDetails
195 = initIfaceTc iface $ \ tc_env_var -> do
196 -- The tc_env_var is freshly allocated, private to
197 -- type-checking this particular interface
198 { -- Get the right set of decls and rules. If we are compiling without -O
199 -- we discard pragmas before typechecking, so that we don't "see"
200 -- information that we shouldn't. From a versioning point of view
201 -- It's not actually *wrong* to do so, but in fact GHCi is unable
202 -- to handle unboxed tuples, so it must not see unfoldings.
203 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
205 -- Typecheck the decls. This is done lazily, so that the knot-tying
206 -- within this single module work out right. In the If monad there is
207 -- no global envt for the current interface; instead, the knot is tied
208 -- through the if_rec_types field of IfGblEnv
209 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
210 ; let type_env = mkNameEnv names_w_things
211 ; writeMutVar tc_env_var type_env
213 -- Now do those rules and instances
214 ; insts <- mapM tcIfaceInst (mi_insts iface)
215 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
216 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
219 ; exports <- ifaceExportNames (mi_exports iface)
222 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
223 text "Type envt:" <+> ppr type_env])
224 ; return $ ModDetails { md_types = type_env
226 , md_fam_insts = fam_insts
228 , md_exports = exports
234 %************************************************************************
236 Type and class declarations
238 %************************************************************************
241 tcHiBootIface :: Module -> TcRn ModDetails
242 -- Load the hi-boot iface for the module being compiled,
243 -- if it indeed exists in the transitive closure of imports
244 -- Return the ModDetails, empty if no hi-boot iface
246 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
249 ; if not (isOneShot mode)
250 -- In --make and interactive mode, if this module has an hs-boot file
251 -- we'll have compiled it already, and it'll be in the HPT
253 -- We check wheher the interface is a *boot* interface.
254 -- It can happen (when using GHC from Visual Studio) that we
255 -- compile a module in TypecheckOnly mode, with a stable,
256 -- fully-populated HPT. In that case the boot interface isn't there
257 -- (it's been replaced by the mother module) so we can't check it.
258 -- And that's fine, because if M's ModInfo is in the HPT, then
259 -- it's been compiled once, and we don't need to check the boot iface
260 then do { hpt <- getHpt
261 ; case lookupUFM hpt (moduleName mod) of
262 Just info | mi_boot (hm_iface info)
263 -> return (hm_details info)
264 other -> return emptyModDetails }
267 -- OK, so we're in one-shot mode.
268 -- In that case, we're read all the direct imports by now,
269 -- so eps_is_boot will record if any of our imports mention us by
270 -- way of hi-boot file
272 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
273 Nothing -> return emptyModDetails ; -- The typical case
275 Just (_, False) -> failWithTc moduleLoop ;
276 -- Someone below us imported us!
277 -- This is a loop with no hi-boot in the way
279 Just (_mod, True) -> -- There's a hi-boot interface below us
281 do { read_result <- findAndReadIface
285 ; case read_result of
286 Failed err -> failWithTc (elaborate err)
287 Succeeded (iface, _path) -> typecheckIface iface
290 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
291 <+> ptext SLIT("to compare against the Real Thing")
293 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
294 <+> ptext SLIT("depends on itself")
296 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
297 quotes (ppr mod) <> colon) 4 err
301 %************************************************************************
303 Type and class declarations
305 %************************************************************************
307 When typechecking a data type decl, we *lazily* (via forkM) typecheck
308 the constructor argument types. This is in the hope that we may never
309 poke on those argument types, and hence may never need to load the
310 interface files for types mentioned in the arg types.
313 data Foo.S = MkS Baz.T
314 Mabye we can get away without even loading the interface for Baz!
316 This is not just a performance thing. Suppose we have
317 data Foo.S = MkS Baz.T
318 data Baz.T = MkT Foo.S
319 (in different interface files, of course).
320 Now, first we load and typecheck Foo.S, and add it to the type envt.
321 If we do explore MkS's argument, we'll load and typecheck Baz.T.
322 If we explore MkT's argument we'll find Foo.S already in the envt.
324 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
325 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
326 which isn't done yet.
328 All very cunning. However, there is a rather subtle gotcha which bit
329 me when developing this stuff. When we typecheck the decl for S, we
330 extend the type envt with S, MkS, and all its implicit Ids. Suppose
331 (a bug, but it happened) that the list of implicit Ids depended in
332 turn on the constructor arg types. Then the following sequence of
334 * we build a thunk <t> for the constructor arg tys
335 * we build a thunk for the extended type environment (depends on <t>)
336 * we write the extended type envt into the global EPS mutvar
338 Now we look something up in the type envt
340 * which reads the global type envt out of the global EPS mutvar
341 * but that depends in turn on <t>
343 It's subtle, because, it'd work fine if we typechecked the constructor args
344 eagerly -- they don't need the extended type envt. They just get the extended
345 type envt by accident, because they look at it later.
347 What this means is that the implicitTyThings MUST NOT DEPEND on any of
352 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
356 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
357 = do { name <- lookupIfaceTop occ_name
358 ; ty <- tcIfaceType iface_type
359 ; info <- tcIdInfo ignore_prags name ty info
360 ; return (AnId (mkVanillaGlobal name ty info)) }
362 tcIfaceDecl ignore_prags
363 (IfaceData {ifName = occ_name,
365 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
368 ifGeneric = want_generic,
369 ifFamInst = mb_family })
370 = do { tc_name <- lookupIfaceTop occ_name
371 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
373 { tycon <- fixM ( \ tycon -> do
374 { stupid_theta <- tcIfaceCtxt ctxt
377 Nothing -> return Nothing
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 dfun_occ
515 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
516 ; return (mkImportedInstance cls mb_tcs' orph dfun oflag) }
518 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
519 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
520 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
521 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
522 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
523 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
525 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
526 ; return (mkImportedFamInst fam mb_tcs' tycon') }
530 %************************************************************************
534 %************************************************************************
536 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
537 are in the type environment. However, remember that typechecking a Rule may
538 (as a side effect) augment the type envt, and so we may need to iterate the process.
541 tcIfaceRules :: Bool -- True <=> ignore rules
544 tcIfaceRules ignore_prags if_rules
545 | ignore_prags = return []
546 | otherwise = mapM tcIfaceRule if_rules
548 tcIfaceRule :: IfaceRule -> IfL CoreRule
549 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
550 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
552 = do { ~(bndrs', args', rhs') <-
553 -- Typecheck the payload lazily, in the hope it'll never be looked at
554 forkM (ptext SLIT("Rule") <+> ftext name) $
555 bindIfaceBndrs bndrs $ \ bndrs' ->
556 do { args' <- mappM tcIfaceExpr args
557 ; rhs' <- tcIfaceExpr rhs
558 ; return (bndrs', args', rhs') }
559 ; let mb_tcs = map ifTopFreeName args
561 ; let this_module = if_mod lcl
562 ; returnM (Rule { ru_name = name, ru_fn = fn, ru_act = act,
563 ru_bndrs = bndrs', ru_args = args',
564 ru_rhs = rhs', ru_orph = orph,
566 ru_local = nameModule fn == this_module }) }
568 -- This function *must* mirror exactly what Rules.topFreeName does
569 -- We could have stored the ru_rough field in the iface file
570 -- but that would be redundant, I think.
571 -- The only wrinkle is that we must not be deceived by
572 -- type syononyms at the top of a type arg. Since
573 -- we can't tell at this point, we are careful not
574 -- to write them out in coreRuleToIfaceRule
575 ifTopFreeName :: IfaceExpr -> Maybe Name
576 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
577 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
578 ifTopFreeName (IfaceExt n) = Just n
579 ifTopFreeName other = Nothing
583 %************************************************************************
587 %************************************************************************
590 tcIfaceType :: IfaceType -> IfL Type
591 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
592 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
593 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
594 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
595 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
596 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
598 tcIfaceTypes tys = mapM tcIfaceType tys
600 -----------------------------------------
601 tcIfacePredType :: IfacePredType -> IfL PredType
602 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
603 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
604 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
606 -----------------------------------------
607 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
608 tcIfaceCtxt sts = mappM tcIfacePredType sts
612 %************************************************************************
616 %************************************************************************
619 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
620 tcIfaceExpr (IfaceType ty)
621 = tcIfaceType ty `thenM` \ ty' ->
624 tcIfaceExpr (IfaceLcl name)
625 = tcIfaceLclId name `thenM` \ id ->
628 tcIfaceExpr (IfaceExt gbl)
629 = tcIfaceExtId gbl `thenM` \ id ->
632 tcIfaceExpr (IfaceLit lit)
635 tcIfaceExpr (IfaceFCall cc ty)
636 = tcIfaceType ty `thenM` \ ty' ->
637 newUnique `thenM` \ u ->
638 returnM (Var (mkFCallId u cc ty'))
640 tcIfaceExpr (IfaceTuple boxity args)
641 = mappM tcIfaceExpr args `thenM` \ args' ->
643 -- Put the missing type arguments back in
644 con_args = map (Type . exprType) args' ++ args'
646 returnM (mkApps (Var con_id) con_args)
649 con_id = dataConWorkId (tupleCon boxity arity)
652 tcIfaceExpr (IfaceLam bndr body)
653 = bindIfaceBndr bndr $ \ bndr' ->
654 tcIfaceExpr body `thenM` \ body' ->
655 returnM (Lam bndr' body')
657 tcIfaceExpr (IfaceApp fun arg)
658 = tcIfaceExpr fun `thenM` \ fun' ->
659 tcIfaceExpr arg `thenM` \ arg' ->
660 returnM (App fun' arg')
662 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
663 = tcIfaceExpr scrut `thenM` \ scrut' ->
664 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
666 scrut_ty = exprType scrut'
667 case_bndr' = mkLocalId case_bndr_name scrut_ty
668 tc_app = splitTyConApp scrut_ty
669 -- NB: Won't always succeed (polymoprhic case)
670 -- but won't be demanded in those cases
671 -- NB: not tcSplitTyConApp; we are looking at Core here
672 -- look through non-rec newtypes to find the tycon that
673 -- corresponds to the datacon in this case alternative
675 extendIfaceIdEnv [case_bndr'] $
676 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
677 tcIfaceType ty `thenM` \ ty' ->
678 returnM (Case scrut' case_bndr' ty' alts')
680 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
681 = tcIfaceExpr rhs `thenM` \ rhs' ->
682 bindIfaceId bndr $ \ bndr' ->
683 tcIfaceExpr body `thenM` \ body' ->
684 returnM (Let (NonRec bndr' rhs') body')
686 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
687 = bindIfaceIds bndrs $ \ bndrs' ->
688 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
689 tcIfaceExpr body `thenM` \ body' ->
690 returnM (Let (Rec (bndrs' `zip` rhss')) body')
692 (bndrs, rhss) = unzip pairs
694 tcIfaceExpr (IfaceCast expr co) = do
695 expr' <- tcIfaceExpr expr
696 co' <- tcIfaceType co
697 returnM (Cast expr' co')
699 tcIfaceExpr (IfaceNote note expr)
700 = tcIfaceExpr expr `thenM` \ expr' ->
702 IfaceInlineMe -> returnM (Note InlineMe expr')
703 IfaceSCC cc -> returnM (Note (SCC cc) expr')
704 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
706 -------------------------
707 tcIfaceAlt _ (IfaceDefault, names, rhs)
708 = ASSERT( null names )
709 tcIfaceExpr rhs `thenM` \ rhs' ->
710 returnM (DEFAULT, [], rhs')
712 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
713 = ASSERT( null names )
714 tcIfaceExpr rhs `thenM` \ rhs' ->
715 returnM (LitAlt lit, [], rhs')
717 -- A case alternative is made quite a bit more complicated
718 -- by the fact that we omit type annotations because we can
719 -- work them out. True enough, but its not that easy!
720 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
721 = do { con <- tcIfaceDataCon data_occ
722 ; ASSERT2( con `elem` tyConDataCons tycon,
723 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
724 tcIfaceDataAlt con inst_tys arg_strs rhs }
726 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
727 = ASSERT( isTupleTyCon tycon )
728 do { let [data_con] = tyConDataCons tycon
729 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
731 tcIfaceDataAlt con inst_tys arg_strs rhs
732 = do { us <- newUniqueSupply
733 ; let uniqs = uniqsFromSupply us
734 ; let (ex_tvs, co_tvs, arg_ids)
735 = dataConRepFSInstPat arg_strs uniqs con inst_tys
736 all_tvs = ex_tvs ++ co_tvs
738 ; rhs' <- extendIfaceTyVarEnv all_tvs $
739 extendIfaceIdEnv arg_ids $
741 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
746 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
747 tcExtCoreBindings [] = return []
748 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
750 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
751 do_one (IfaceNonRec bndr rhs) thing_inside
752 = do { rhs' <- tcIfaceExpr rhs
753 ; bndr' <- newExtCoreBndr bndr
754 ; extendIfaceIdEnv [bndr'] $ do
755 { core_binds <- thing_inside
756 ; return (NonRec bndr' rhs' : core_binds) }}
758 do_one (IfaceRec pairs) thing_inside
759 = do { bndrs' <- mappM newExtCoreBndr bndrs
760 ; extendIfaceIdEnv bndrs' $ do
761 { rhss' <- mappM tcIfaceExpr rhss
762 ; core_binds <- thing_inside
763 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
765 (bndrs,rhss) = unzip pairs
769 %************************************************************************
773 %************************************************************************
776 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
777 tcIdInfo ignore_prags name ty info
778 | ignore_prags = return vanillaIdInfo
779 | otherwise = case info of
780 NoInfo -> return vanillaIdInfo
781 HasInfo info -> foldlM tcPrag init_info info
783 -- Set the CgInfo to something sensible but uninformative before
784 -- we start; default assumption is that it has CAFs
785 init_info = vanillaIdInfo
787 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
788 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
789 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
791 -- The next two are lazy, so they don't transitively suck stuff in
792 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
793 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
794 tcPrag info (HsUnfold expr)
795 = tcPragExpr name expr `thenM` \ maybe_expr' ->
797 -- maybe_expr' doesn't get looked at if the unfolding
798 -- is never inspected; so the typecheck doesn't even happen
799 unfold_info = case maybe_expr' of
800 Nothing -> noUnfolding
801 Just expr' -> mkTopUnfolding expr'
803 returnM (info `setUnfoldingInfoLazily` unfold_info)
807 tcWorkerInfo ty info wkr arity
808 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
810 -- We return without testing maybe_wkr_id, but as soon as info is
811 -- looked at we will test it. That's ok, because its outside the
812 -- knot; and there seems no big reason to further defer the
813 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
814 -- over the unfolding until it's actually used does seem worth while.)
815 ; us <- newUniqueSupply
817 ; returnM (case mb_wkr_id of
819 Just wkr_id -> add_wkr_info us wkr_id info) }
821 doc = text "Worker for" <+> ppr wkr
822 add_wkr_info us wkr_id info
823 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
824 `setWorkerInfo` HasWorker wkr_id arity
826 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
828 -- We are relying here on strictness info always appearing
829 -- before worker info, fingers crossed ....
830 strict_sig = case newStrictnessInfo info of
832 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
835 For unfoldings we try to do the job lazily, so that we never type check
836 an unfolding that isn't going to be looked at.
839 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
842 tcIfaceExpr expr `thenM` \ core_expr' ->
844 -- Check for type consistency in the unfolding
845 ifOptM Opt_DoCoreLinting (
846 get_in_scope_ids `thenM` \ in_scope ->
847 case lintUnfolding noSrcLoc in_scope core_expr' of
848 Nothing -> returnM ()
849 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
854 doc = text "Unfolding of" <+> ppr name
855 get_in_scope_ids -- Urgh; but just for linting
857 do { env <- getGblEnv
858 ; case if_rec_types env of {
859 Nothing -> return [] ;
860 Just (_, get_env) -> do
861 { type_env <- get_env
862 ; return (typeEnvIds type_env) }}}
867 %************************************************************************
869 Getting from Names to TyThings
871 %************************************************************************
874 tcIfaceGlobal :: Name -> IfL TyThing
876 | Just thing <- wiredInNameTyThing_maybe name
877 -- Wired-in things include TyCons, DataCons, and Ids
878 = do { ifCheckWiredInThing name; return thing }
880 = do { (eps,hpt) <- getEpsAndHpt
882 ; case lookupType dflags hpt (eps_PTE eps) name of {
883 Just thing -> return thing ;
887 ; case if_rec_types env of {
888 Just (mod, get_type_env)
889 | nameIsLocalOrFrom mod name
890 -> do -- It's defined in the module being compiled
891 { type_env <- setLclEnv () get_type_env -- yuk
892 ; case lookupNameEnv type_env name of
893 Just thing -> return thing
894 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
895 (ppr name $$ ppr type_env) }
899 { mb_thing <- importDecl name -- It's imported; go get it
901 Failed err -> failIfM err
902 Succeeded thing -> return thing
905 ifCheckWiredInThing :: Name -> IfL ()
906 -- Even though we are in an interface file, we want to make
907 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
908 -- Ditto want to ensure that RULES are loaded too
909 ifCheckWiredInThing name
910 = do { mod <- getIfModule
911 -- Check whether we are typechecking the interface for this
912 -- very module. E.g when compiling the base library in --make mode
913 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
914 -- the HPT, so without the test we'll demand-load it into the PIT!
915 -- C.f. the same test in checkWiredInTyCon above
916 ; unless (mod == nameModule name)
917 (loadWiredInHomeIface name) }
919 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
920 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
921 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
922 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
923 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
924 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
925 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
926 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
927 ; return (check_tc (tyThingTyCon thing)) }
930 check_tc tc = case toIfaceTyCon tc of
932 other -> pprTrace "check_tc" (ppr tc) tc
936 -- we should be okay just returning Kind constructors without extra loading
937 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
938 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
939 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
940 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
941 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
943 -- Even though we are in an interface file, we want to make
944 -- sure the instances and RULES of this tycon are loaded
945 -- Imagine: f :: Double -> Double
946 tcWiredInTyCon :: TyCon -> IfL TyCon
947 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
950 tcIfaceClass :: Name -> IfL Class
951 tcIfaceClass name = do { thing <- tcIfaceGlobal name
952 ; return (tyThingClass thing) }
954 tcIfaceDataCon :: Name -> IfL DataCon
955 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
957 ADataCon dc -> return dc
958 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
960 tcIfaceExtId :: Name -> IfL Id
961 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
964 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
967 %************************************************************************
971 %************************************************************************
974 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
975 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
976 = bindIfaceId bndr thing_inside
977 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
978 = bindIfaceTyVar bndr thing_inside
980 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
981 bindIfaceBndrs [] thing_inside = thing_inside []
982 bindIfaceBndrs (b:bs) thing_inside
983 = bindIfaceBndr b $ \ b' ->
984 bindIfaceBndrs bs $ \ bs' ->
985 thing_inside (b':bs')
987 -----------------------
988 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
989 bindIfaceId (occ, ty) thing_inside
990 = do { name <- newIfaceName (mkVarOccFS occ)
991 ; ty' <- tcIfaceType ty
992 ; let { id = mkLocalId name ty' }
993 ; extendIfaceIdEnv [id] (thing_inside id) }
995 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
996 bindIfaceIds bndrs thing_inside
997 = do { names <- newIfaceNames (map mkVarOccFS occs)
998 ; tys' <- mappM tcIfaceType tys
999 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
1000 ; extendIfaceIdEnv ids (thing_inside ids) }
1002 (occs,tys) = unzip bndrs
1005 -----------------------
1006 newExtCoreBndr :: IfaceIdBndr -> IfL Id
1007 newExtCoreBndr (var, ty)
1008 = do { mod <- getIfModule
1009 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcLoc
1010 ; ty' <- tcIfaceType ty
1011 ; return (mkLocalId name ty') }
1013 -----------------------
1014 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1015 bindIfaceTyVar (occ,kind) thing_inside
1016 = do { name <- newIfaceName (mkTyVarOcc occ)
1017 ; tyvar <- mk_iface_tyvar name kind
1018 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1020 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1021 bindIfaceTyVars bndrs thing_inside
1022 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1023 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1024 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1026 (occs,kinds) = unzip bndrs
1028 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1029 mk_iface_tyvar name ifKind = do { kind <- tcIfaceType ifKind
1030 ; return (mkTyVar name kind)