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, 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,
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 (LocalTop dfun_occ)
515 ; cls' <- lookupIfaceExt cls
516 ; mb_tcs' <- mapM tc_rough mb_tcs
517 ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
519 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
520 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
521 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
522 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
523 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
524 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
526 ; fam' <- lookupIfaceExt fam
527 ; mb_tcs' <- mapM tc_rough mb_tcs
528 ; return (mkImportedFamInst fam' mb_tcs' tycon') }
530 tc_rough Nothing = return Nothing
531 tc_rough (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
535 %************************************************************************
539 %************************************************************************
541 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
542 are in the type environment. However, remember that typechecking a Rule may
543 (as a side effect) augment the type envt, and so we may need to iterate the process.
546 tcIfaceRules :: Bool -- True <=> ignore rules
549 tcIfaceRules ignore_prags if_rules
550 | ignore_prags = return []
551 | otherwise = mapM tcIfaceRule if_rules
553 tcIfaceRule :: IfaceRule -> IfL CoreRule
554 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
555 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
557 = do { fn' <- lookupIfaceExt fn
558 ; ~(bndrs', args', rhs') <-
559 -- Typecheck the payload lazily, in the hope it'll never be looked at
560 forkM (ptext SLIT("Rule") <+> ftext name) $
561 bindIfaceBndrs bndrs $ \ bndrs' ->
562 do { args' <- mappM tcIfaceExpr args
563 ; rhs' <- tcIfaceExpr rhs
564 ; return (bndrs', args', rhs') }
565 ; mb_tcs <- mapM ifTopFreeName args
566 ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act,
567 ru_bndrs = bndrs', ru_args = args',
568 ru_rhs = rhs', ru_orph = orph,
570 ru_local = isLocalIfaceExtName fn }) }
572 -- This function *must* mirror exactly what Rules.topFreeName does
573 -- We could have stored the ru_rough field in the iface file
574 -- but that would be redundant, I think.
575 -- The only wrinkle is that we must not be deceived by
576 -- type syononyms at the top of a type arg. Since
577 -- we can't tell at this point, we are careful not
578 -- to write them out in coreRuleToIfaceRule
579 ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
580 ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
581 = do { n <- lookupIfaceTc tc
583 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
584 ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
586 ifTopFreeName other = return Nothing
590 %************************************************************************
594 %************************************************************************
597 tcIfaceType :: IfaceType -> IfL Type
598 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
599 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
600 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
601 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
602 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
603 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
605 tcIfaceTypes tys = mapM tcIfaceType tys
607 -----------------------------------------
608 tcIfacePredType :: IfacePredType -> IfL PredType
609 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
610 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
611 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
613 -----------------------------------------
614 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
615 tcIfaceCtxt sts = mappM tcIfacePredType sts
619 %************************************************************************
623 %************************************************************************
626 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
627 tcIfaceExpr (IfaceType ty)
628 = tcIfaceType ty `thenM` \ ty' ->
631 tcIfaceExpr (IfaceLcl name)
632 = tcIfaceLclId name `thenM` \ id ->
635 tcIfaceExpr (IfaceExt gbl)
636 = tcIfaceExtId gbl `thenM` \ id ->
639 tcIfaceExpr (IfaceLit lit)
642 tcIfaceExpr (IfaceFCall cc ty)
643 = tcIfaceType ty `thenM` \ ty' ->
644 newUnique `thenM` \ u ->
645 returnM (Var (mkFCallId u cc ty'))
647 tcIfaceExpr (IfaceTuple boxity args)
648 = mappM tcIfaceExpr args `thenM` \ args' ->
650 -- Put the missing type arguments back in
651 con_args = map (Type . exprType) args' ++ args'
653 returnM (mkApps (Var con_id) con_args)
656 con_id = dataConWorkId (tupleCon boxity arity)
659 tcIfaceExpr (IfaceLam bndr body)
660 = bindIfaceBndr bndr $ \ bndr' ->
661 tcIfaceExpr body `thenM` \ body' ->
662 returnM (Lam bndr' body')
664 tcIfaceExpr (IfaceApp fun arg)
665 = tcIfaceExpr fun `thenM` \ fun' ->
666 tcIfaceExpr arg `thenM` \ arg' ->
667 returnM (App fun' arg')
669 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
670 = tcIfaceExpr scrut `thenM` \ scrut' ->
671 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
673 scrut_ty = exprType scrut'
674 case_bndr' = mkLocalId case_bndr_name scrut_ty
675 tc_app = splitTyConApp scrut_ty
676 -- NB: Won't always succeed (polymoprhic case)
677 -- but won't be demanded in those cases
678 -- NB: not tcSplitTyConApp; we are looking at Core here
679 -- look through non-rec newtypes to find the tycon that
680 -- corresponds to the datacon in this case alternative
682 extendIfaceIdEnv [case_bndr'] $
683 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
684 tcIfaceType ty `thenM` \ ty' ->
685 returnM (Case scrut' case_bndr' ty' alts')
687 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
688 = tcIfaceExpr rhs `thenM` \ rhs' ->
689 bindIfaceId bndr $ \ bndr' ->
690 tcIfaceExpr body `thenM` \ body' ->
691 returnM (Let (NonRec bndr' rhs') body')
693 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
694 = bindIfaceIds bndrs $ \ bndrs' ->
695 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
696 tcIfaceExpr body `thenM` \ body' ->
697 returnM (Let (Rec (bndrs' `zip` rhss')) body')
699 (bndrs, rhss) = unzip pairs
701 tcIfaceExpr (IfaceCast expr co) = do
702 expr' <- tcIfaceExpr expr
703 co' <- tcIfaceType co
704 returnM (Cast expr' co')
706 tcIfaceExpr (IfaceNote note expr)
707 = tcIfaceExpr expr `thenM` \ expr' ->
709 IfaceInlineMe -> returnM (Note InlineMe expr')
710 IfaceSCC cc -> returnM (Note (SCC cc) expr')
711 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
713 -------------------------
714 tcIfaceAlt _ (IfaceDefault, names, rhs)
715 = ASSERT( null names )
716 tcIfaceExpr rhs `thenM` \ rhs' ->
717 returnM (DEFAULT, [], rhs')
719 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
720 = ASSERT( null names )
721 tcIfaceExpr rhs `thenM` \ rhs' ->
722 returnM (LitAlt lit, [], rhs')
724 -- A case alternative is made quite a bit more complicated
725 -- by the fact that we omit type annotations because we can
726 -- work them out. True enough, but its not that easy!
727 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
728 = do { let tycon_mod = nameModule (tyConName tycon)
729 ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
730 ; ASSERT2( con `elem` tyConDataCons tycon,
731 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
732 tcIfaceDataAlt con inst_tys arg_strs rhs }
734 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
735 = ASSERT( isTupleTyCon tycon )
736 do { let [data_con] = tyConDataCons tycon
737 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
739 tcIfaceDataAlt con inst_tys arg_strs rhs
740 = do { us <- newUniqueSupply
741 ; let uniqs = uniqsFromSupply us
742 ; let (ex_tvs, co_tvs, arg_ids)
743 = dataConRepFSInstPat arg_strs uniqs con inst_tys
744 all_tvs = ex_tvs ++ co_tvs
746 ; rhs' <- extendIfaceTyVarEnv all_tvs $
747 extendIfaceIdEnv arg_ids $
749 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
754 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
755 tcExtCoreBindings [] = return []
756 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
758 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
759 do_one (IfaceNonRec bndr rhs) thing_inside
760 = do { rhs' <- tcIfaceExpr rhs
761 ; bndr' <- newExtCoreBndr bndr
762 ; extendIfaceIdEnv [bndr'] $ do
763 { core_binds <- thing_inside
764 ; return (NonRec bndr' rhs' : core_binds) }}
766 do_one (IfaceRec pairs) thing_inside
767 = do { bndrs' <- mappM newExtCoreBndr bndrs
768 ; extendIfaceIdEnv bndrs' $ do
769 { rhss' <- mappM tcIfaceExpr rhss
770 ; core_binds <- thing_inside
771 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
773 (bndrs,rhss) = unzip pairs
777 %************************************************************************
781 %************************************************************************
784 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
785 tcIdInfo ignore_prags name ty info
786 | ignore_prags = return vanillaIdInfo
787 | otherwise = case info of
788 NoInfo -> return vanillaIdInfo
789 HasInfo info -> foldlM tcPrag init_info info
791 -- Set the CgInfo to something sensible but uninformative before
792 -- we start; default assumption is that it has CAFs
793 init_info = vanillaIdInfo
795 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
796 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
797 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
799 -- The next two are lazy, so they don't transitively suck stuff in
800 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
801 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
802 tcPrag info (HsUnfold expr)
803 = tcPragExpr name expr `thenM` \ maybe_expr' ->
805 -- maybe_expr' doesn't get looked at if the unfolding
806 -- is never inspected; so the typecheck doesn't even happen
807 unfold_info = case maybe_expr' of
808 Nothing -> noUnfolding
809 Just expr' -> mkTopUnfolding expr'
811 returnM (info `setUnfoldingInfoLazily` unfold_info)
815 tcWorkerInfo ty info wkr arity
816 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
818 -- We return without testing maybe_wkr_id, but as soon as info is
819 -- looked at we will test it. That's ok, because its outside the
820 -- knot; and there seems no big reason to further defer the
821 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
822 -- over the unfolding until it's actually used does seem worth while.)
823 ; us <- newUniqueSupply
825 ; returnM (case mb_wkr_id of
827 Just wkr_id -> add_wkr_info us wkr_id info) }
829 doc = text "Worker for" <+> ppr wkr
830 add_wkr_info us wkr_id info
831 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
832 `setWorkerInfo` HasWorker wkr_id arity
834 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
836 -- We are relying here on strictness info always appearing
837 -- before worker info, fingers crossed ....
838 strict_sig = case newStrictnessInfo info of
840 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
843 For unfoldings we try to do the job lazily, so that we never type check
844 an unfolding that isn't going to be looked at.
847 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
850 tcIfaceExpr expr `thenM` \ core_expr' ->
852 -- Check for type consistency in the unfolding
853 ifOptM Opt_DoCoreLinting (
854 get_in_scope_ids `thenM` \ in_scope ->
855 case lintUnfolding noSrcLoc in_scope core_expr' of
856 Nothing -> returnM ()
857 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
862 doc = text "Unfolding of" <+> ppr name
863 get_in_scope_ids -- Urgh; but just for linting
865 do { env <- getGblEnv
866 ; case if_rec_types env of {
867 Nothing -> return [] ;
868 Just (_, get_env) -> do
869 { type_env <- get_env
870 ; return (typeEnvIds type_env) }}}
875 %************************************************************************
877 Getting from Names to TyThings
879 %************************************************************************
882 tcIfaceGlobal :: Name -> IfL TyThing
884 | Just thing <- wiredInNameTyThing_maybe name
885 -- Wired-in things include TyCons, DataCons, and Ids
886 = do { ifCheckWiredInThing name; return thing }
888 = do { (eps,hpt) <- getEpsAndHpt
890 ; case lookupType dflags hpt (eps_PTE eps) name of {
891 Just thing -> return thing ;
895 ; case if_rec_types env of {
896 Just (mod, get_type_env)
897 | nameIsLocalOrFrom mod name
898 -> do -- It's defined in the module being compiled
899 { type_env <- setLclEnv () get_type_env -- yuk
900 ; case lookupNameEnv type_env name of
901 Just thing -> return thing
902 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
903 (ppr name $$ ppr type_env) }
907 { mb_thing <- importDecl name -- It's imported; go get it
909 Failed err -> failIfM err
910 Succeeded thing -> return thing
913 ifCheckWiredInThing :: Name -> IfL ()
914 -- Even though we are in an interface file, we want to make
915 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
916 -- Ditto want to ensure that RULES are loaded too
917 ifCheckWiredInThing name
918 = do { mod <- getIfModule
919 -- Check whether we are typechecking the interface for this
920 -- very module. E.g when compiling the base library in --make mode
921 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
922 -- the HPT, so without the test we'll demand-load it into the PIT!
923 -- C.f. the same test in checkWiredInTyCon above
924 ; unless (mod == nameModule name)
925 (loadWiredInHomeIface name) }
927 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
928 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
929 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
930 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
931 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
932 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
933 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
934 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
935 ; thing <- tcIfaceGlobal name
936 ; return (check_tc (tyThingTyCon thing)) }
939 check_tc tc = case toIfaceTyCon (error "urk") tc of
941 other -> pprTrace "check_tc" (ppr tc) tc
945 -- we should be okay just returning Kind constructors without extra loading
946 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
947 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
948 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
949 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
950 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
952 -- Even though we are in an interface file, we want to make
953 -- sure the instances and RULES of this tycon are loaded
954 -- Imagine: f :: Double -> Double
955 tcWiredInTyCon :: TyCon -> IfL TyCon
956 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
959 tcIfaceClass :: IfaceExtName -> IfL Class
960 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
961 ; thing <- tcIfaceGlobal name
962 ; return (tyThingClass thing) }
964 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
965 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
966 ; thing <- tcIfaceGlobal name
968 ADataCon dc -> return dc
969 other -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
971 tcIfaceExtId :: IfaceExtName -> IfL Id
972 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
973 ; thing <- tcIfaceGlobal name
976 other -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
979 %************************************************************************
983 %************************************************************************
986 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
987 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
988 = bindIfaceId bndr thing_inside
989 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
990 = bindIfaceTyVar bndr thing_inside
992 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
993 bindIfaceBndrs [] thing_inside = thing_inside []
994 bindIfaceBndrs (b:bs) thing_inside
995 = bindIfaceBndr b $ \ b' ->
996 bindIfaceBndrs bs $ \ bs' ->
997 thing_inside (b':bs')
999 -----------------------
1000 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
1001 bindIfaceId (occ, ty) thing_inside
1002 = do { name <- newIfaceName (mkVarOccFS occ)
1003 ; ty' <- tcIfaceType ty
1004 ; let { id = mkLocalId name ty' }
1005 ; extendIfaceIdEnv [id] (thing_inside id) }
1007 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
1008 bindIfaceIds bndrs thing_inside
1009 = do { names <- newIfaceNames (map mkVarOccFS occs)
1010 ; tys' <- mappM tcIfaceType tys
1011 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
1012 ; extendIfaceIdEnv ids (thing_inside ids) }
1014 (occs,tys) = unzip bndrs
1017 -----------------------
1018 newExtCoreBndr :: IfaceIdBndr -> IfL Id
1019 newExtCoreBndr (var, ty)
1020 = do { mod <- getIfModule
1021 ; name <- newGlobalBinder mod (mkVarOccFS var) Nothing noSrcLoc
1022 ; ty' <- tcIfaceType ty
1023 ; return (mkLocalId name ty') }
1025 -----------------------
1026 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1027 bindIfaceTyVar (occ,kind) thing_inside
1028 = do { name <- newIfaceName (mkTyVarOcc occ)
1029 ; tyvar <- mk_iface_tyvar name kind
1030 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1032 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1033 bindIfaceTyVars bndrs thing_inside
1034 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1035 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1036 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1038 (occs,kinds) = unzip bndrs
1040 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1041 mk_iface_tyvar name ifKind = do { kind <- tcIfaceType ifKind
1042 ; return (mkTyVar name kind)