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, tcIfaceRule, tcIfaceGlobal,
13 #include "HsVersions.h"
16 import LoadIface ( loadInterface, loadWiredInHomeIface,
17 loadDecls, findAndReadIface )
18 import IfaceEnv ( lookupIfaceTop, lookupIfaceExt, newGlobalBinder,
19 extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
20 tcIfaceTyVar, tcIfaceLclId, lookupIfaceTc,
21 newIfaceName, newIfaceNames, ifaceExportNames )
22 import BuildTyCl ( buildSynTyCon, buildAlgTyCon, buildDataCon,
24 mkAbstractTyConRhs, mkOpenDataTyConRhs,
25 mkOpenNewTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
27 import Type ( liftedTypeKind, splitTyConApp, mkTyConApp,
28 liftedTypeKindTyCon, unliftedTypeKindTyCon,
29 openTypeKindTyCon, argTypeKindTyCon,
31 mkTyVarTys, ThetaType )
32 import TypeRep ( Type(..), PredType(..) )
33 import TyCon ( TyCon, tyConName, SynTyConRhs(..),
34 AlgTyConParent(..), setTyConArgPoss )
35 import HscTypes ( ExternalPackageState(..),
36 TyThing(..), tyThingClass, tyThingTyCon,
37 ModIface(..), ModDetails(..), HomeModInfo(..),
38 emptyModDetails, lookupTypeEnv, lookupType,
39 typeEnvIds, mkDetailsFamInstCache )
40 import InstEnv ( Instance(..), mkImportedInstance )
41 import FamInstEnv ( extractFamInsts )
43 import CoreUtils ( exprType, dataConRepFSInstPat )
45 import CoreLint ( lintUnfolding )
46 import WorkWrap ( mkWrapper )
47 import Id ( Id, mkVanillaGlobal, mkLocalId )
48 import MkId ( mkFCallId )
49 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
50 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
51 setArityInfo, setInlinePragInfo, setCafInfo,
52 vanillaIdInfo, newStrictnessInfo )
53 import Class ( Class )
54 import TyCon ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
55 import DataCon ( DataCon, dataConWorkId, dataConExTyVars, dataConInstArgTys )
56 import TysWiredIn ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
57 import Var ( TyVar, mkTyVar, tyVarKind )
58 import Name ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
59 nameOccName, wiredInNameTyThing_maybe )
61 import OccName ( OccName, mkVarOccFS, mkTyVarOcc, occNameSpace,
62 pprNameSpace, occNameFS )
63 import FastString ( FastString )
64 import Module ( Module, moduleName )
65 import UniqFM ( lookupUFM )
66 import UniqSupply ( initUs_, uniqsFromSupply )
68 import ErrUtils ( Message )
69 import Maybes ( MaybeErr(..) )
70 import SrcLoc ( noSrcLoc )
71 import Util ( zipWithEqual, equalLength, splitAtList )
72 import DynFlags ( DynFlag(..), isOneShot )
74 import List ( elemIndex)
75 import Maybe ( catMaybes )
76 import Monad ( liftM )
85 An IfaceDecl is populated with RdrNames, and these are not renamed to
86 Names before typechecking, because there should be no scope errors etc.
88 -- For (b) consider: f = $(...h....)
89 -- where h is imported, and calls f via an hi-boot file.
90 -- This is bad! But it is not seen as a staging error, because h
91 -- is indeed imported. We don't want the type-checker to black-hole
92 -- when simplifying and compiling the splice!
94 -- Simple solution: discard any unfolding that mentions a variable
95 -- bound in this module (and hence not yet processed).
96 -- The discarding happens when forkM finds a type error.
98 %************************************************************************
100 %* tcImportDecl is the key function for "faulting in" *
103 %************************************************************************
105 The main idea is this. We are chugging along type-checking source code, and
106 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
107 it in the EPS type envt. So it
109 2 gets the decl for GHC.Base.map
110 3 typechecks it via tcIfaceDecl
111 4 and adds it to the type env in the EPS
113 Note that DURING STEP 4, we may find that map's type mentions a type
114 constructor that also
116 Notice that for imported things we read the current version from the EPS
117 mutable variable. This is important in situations like
119 where the code that e1 expands to might import some defns that
120 also turn out to be needed by the code that e2 expands to.
123 tcImportDecl :: Name -> TcM TyThing
124 -- Entry point for *source-code* uses of importDecl
126 | Just thing <- wiredInNameTyThing_maybe name
127 = do { initIfaceTcRn (loadWiredInHomeIface name)
130 = do { traceIf (text "tcImportDecl" <+> ppr name)
131 ; mb_thing <- initIfaceTcRn (importDecl name)
133 Succeeded thing -> return thing
134 Failed err -> failWithTc err }
136 checkWiredInTyCon :: TyCon -> TcM ()
137 -- Ensure that the home module of the TyCon (and hence its instances)
138 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
139 -- in which case this is a no-op.
141 | not (isWiredInName tc_name)
144 = do { mod <- getModule
145 ; if nameIsLocalOrFrom mod tc_name then
146 -- Don't look for (non-existent) Float.hi when
147 -- compiling Float.lhs, which mentions Float of course
149 else -- A bit yukky to call initIfaceTcRn here
150 initIfaceTcRn (loadWiredInHomeIface tc_name)
153 tc_name = tyConName tc
155 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
156 -- Get the TyThing for this Name from an interface file
157 -- It's not a wired-in thing -- the caller caught that
159 = ASSERT( not (isWiredInName name) )
162 -- Load the interface, which should populate the PTE
163 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
165 Failed err_msg -> return (Failed err_msg) ;
166 Succeeded iface -> do
168 -- Now look it up again; this time we should find it
170 ; case lookupTypeEnv (eps_PTE eps) name of
171 Just thing -> return (Succeeded thing)
172 Nothing -> return (Failed not_found_msg)
175 nd_doc = ptext SLIT("Need decl for") <+> ppr name
176 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
177 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
178 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
179 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
182 %************************************************************************
184 Type-checking a complete interface
186 %************************************************************************
188 Suppose we discover we don't need to recompile. Then we must type
189 check the old interface file. This is a bit different to the
190 incremental type checking we do as we suck in interface files. Instead
191 we do things similarly as when we are typechecking source decls: we
192 bring into scope the type envt for the interface all at once, using a
193 knot. Remember, the decls aren't necessarily in dependency order --
194 and even if they were, the type decls might be mutually recursive.
197 typecheckIface :: ModIface -- Get the decls from here
198 -> TcRnIf gbl lcl ModDetails
200 = initIfaceTc iface $ \ tc_env_var -> do
201 -- The tc_env_var is freshly allocated, private to
202 -- type-checking this particular interface
203 { -- Get the right set of decls and rules. If we are compiling without -O
204 -- we discard pragmas before typechecking, so that we don't "see"
205 -- information that we shouldn't. From a versioning point of view
206 -- It's not actually *wrong* to do so, but in fact GHCi is unable
207 -- to handle unboxed tuples, so it must not see unfoldings.
208 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
210 -- Load & typecheck the decls
211 ; decl_things <- loadDecls ignore_prags (mi_decls iface)
213 ; let type_env = mkNameEnv decl_things
214 ; writeMutVar tc_env_var type_env
216 -- Now do those rules and instances
217 ; let { rules | ignore_prags = []
218 | otherwise = mi_rules iface
219 ; dfuns = mi_insts iface
221 ; dfuns <- mapM tcIfaceInst dfuns
222 ; rules <- mapM tcIfaceRule rules
225 ; exports <- ifaceExportNames (mi_exports iface)
228 ; return $ ModDetails { md_types = type_env
230 , md_fam_insts = mkDetailsFamInstCache type_env
232 , md_exports = exports
238 %************************************************************************
240 Type and class declarations
242 %************************************************************************
245 tcHiBootIface :: Module -> TcRn ModDetails
246 -- Load the hi-boot iface for the module being compiled,
247 -- if it indeed exists in the transitive closure of imports
248 -- Return the ModDetails, empty if no hi-boot iface
250 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
253 ; if not (isOneShot mode)
254 -- In --make and interactive mode, if this module has an hs-boot file
255 -- we'll have compiled it already, and it'll be in the HPT
257 -- We check wheher the interface is a *boot* interface.
258 -- It can happen (when using GHC from Visual Studio) that we
259 -- compile a module in TypecheckOnly mode, with a stable,
260 -- fully-populated HPT. In that case the boot interface isn't there
261 -- (it's been replaced by the mother module) so we can't check it.
262 -- And that's fine, because if M's ModInfo is in the HPT, then
263 -- it's been compiled once, and we don't need to check the boot iface
264 then do { hpt <- getHpt
265 ; case lookupUFM hpt (moduleName mod) of
266 Just info | mi_boot (hm_iface info)
267 -> return (hm_details info)
268 other -> return emptyModDetails }
271 -- OK, so we're in one-shot mode.
272 -- In that case, we're read all the direct imports by now,
273 -- so eps_is_boot will record if any of our imports mention us by
274 -- way of hi-boot file
276 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
277 Nothing -> return emptyModDetails ; -- The typical case
279 Just (_, False) -> failWithTc moduleLoop ;
280 -- Someone below us imported us!
281 -- This is a loop with no hi-boot in the way
283 Just (_mod, True) -> -- There's a hi-boot interface below us
285 do { read_result <- findAndReadIface
289 ; case read_result of
290 Failed err -> failWithTc (elaborate err)
291 Succeeded (iface, _path) -> typecheckIface iface
294 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
295 <+> ptext SLIT("to compare against the Real Thing")
297 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
298 <+> ptext SLIT("depends on itself")
300 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
301 quotes (ppr mod) <> colon) 4 err
305 %************************************************************************
307 Type and class declarations
309 %************************************************************************
311 When typechecking a data type decl, we *lazily* (via forkM) typecheck
312 the constructor argument types. This is in the hope that we may never
313 poke on those argument types, and hence may never need to load the
314 interface files for types mentioned in the arg types.
317 data Foo.S = MkS Baz.T
318 Mabye we can get away without even loading the interface for Baz!
320 This is not just a performance thing. Suppose we have
321 data Foo.S = MkS Baz.T
322 data Baz.T = MkT Foo.S
323 (in different interface files, of course).
324 Now, first we load and typecheck Foo.S, and add it to the type envt.
325 If we do explore MkS's argument, we'll load and typecheck Baz.T.
326 If we explore MkT's argument we'll find Foo.S already in the envt.
328 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
329 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
330 which isn't done yet.
332 All very cunning. However, there is a rather subtle gotcha which bit
333 me when developing this stuff. When we typecheck the decl for S, we
334 extend the type envt with S, MkS, and all its implicit Ids. Suppose
335 (a bug, but it happened) that the list of implicit Ids depended in
336 turn on the constructor arg types. Then the following sequence of
338 * we build a thunk <t> for the constructor arg tys
339 * we build a thunk for the extended type environment (depends on <t>)
340 * we write the extended type envt into the global EPS mutvar
342 Now we look something up in the type envt
344 * which reads the global type envt out of the global EPS mutvar
345 * but that depends in turn on <t>
347 It's subtle, because, it'd work fine if we typechecked the constructor args
348 eagerly -- they don't need the extended type envt. They just get the extended
349 type envt by accident, because they look at it later.
351 What this means is that the implicitTyThings MUST NOT DEPEND on any of
356 tcIfaceDecl :: IfaceDecl -> IfL TyThing
358 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
359 = do { name <- lookupIfaceTop occ_name
360 ; ty <- tcIfaceType iface_type
361 ; info <- tcIdInfo name ty info
362 ; return (AnId (mkVanillaGlobal name ty info)) }
364 tcIfaceDecl (IfaceData {ifName = occ_name,
366 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
369 ifGeneric = want_generic,
370 ifFamInst = mb_family })
371 = do { tc_name <- lookupIfaceTop occ_name
372 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
374 { tycon <- fixM ( \ tycon -> do
375 { stupid_theta <- tcIfaceCtxt ctxt
378 Nothing -> return Nothing
379 Just (IfaceFamInst { ifFamInstTyCon = fam
382 do { famTyCon <- tcIfaceTyCon fam
383 ; insttys <- mapM tcIfaceType tys
384 ; return $ Just (famTyCon, insttys)
386 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
387 ; buildAlgTyCon tc_name tyvars stupid_theta
388 cons is_rec want_generic gadt_syn famInst
390 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
391 ; return (ATyCon tycon)
394 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
395 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
396 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
397 { tc_name <- lookupIfaceTop occ_name
398 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
399 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki
400 else SynonymTyCon rhs_tyki
401 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs))
404 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
405 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
406 ifATs = rdr_ats, ifSigs = rdr_sigs,
408 -- ToDo: in hs-boot files we should really treat abstract classes specially,
409 -- as we do abstract tycons
410 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
411 { cls_name <- lookupIfaceTop occ_name
412 ; ctxt <- tcIfaceCtxt rdr_ctxt
413 ; sigs <- mappM tc_sig rdr_sigs
414 ; fds <- mappM tc_fd rdr_fds
415 ; ats' <- mappM tcIfaceDecl rdr_ats
416 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
417 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
418 ; return (AClass cls) }
420 tc_sig (IfaceClassOp occ dm rdr_ty)
421 = do { op_name <- lookupIfaceTop occ
422 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
423 -- Must be done lazily for just the same reason as the
424 -- context of a data decl: the type sig might mention the
425 -- class being defined
426 ; return (op_name, dm, op_ty) }
428 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
430 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
431 ; tvs2' <- mappM tcIfaceTyVar tvs2
432 ; return (tvs1', tvs2') }
434 -- For each AT argument compute the position of the corresponding class
435 -- parameter in the class head. This will later serve as a permutation
436 -- vector when checking the validity of instance declarations.
437 setTyThingPoss (ATyCon tycon) atTyVars =
438 let classTyVars = map fst tv_bndrs
440 . map ((`elemIndex` classTyVars) . fst)
442 -- There will be no Nothing, as we already passed renaming
444 ATyCon (setTyConArgPoss tycon poss)
445 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
447 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
448 = do { name <- lookupIfaceTop rdr_name
449 ; return (ATyCon (mkForeignTyCon name ext_name
452 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
454 IfAbstractTyCon -> return mkAbstractTyConRhs
455 IfOpenDataTyCon -> return mkOpenDataTyConRhs
456 IfOpenNewTyCon -> return mkOpenNewTyConRhs
457 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
458 ; return (mkDataTyConRhs data_cons) }
459 IfNewTyCon con -> do { data_con <- tc_con_decl con
460 ; mkNewTyConRhs tycon_name tycon data_con }
462 tc_con_decl (IfCon { ifConInfix = is_infix,
463 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
464 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
465 ifConArgTys = args, ifConFields = field_lbls,
466 ifConStricts = stricts})
467 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
468 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
469 { name <- lookupIfaceTop occ
470 ; eq_spec <- tcIfaceEqSpec spec
471 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
472 -- At one stage I thought that this context checking *had*
473 -- to be lazy, because of possible mutual recursion between the
474 -- type and the classe:
476 -- class Real a where { toRat :: a -> Ratio Integer }
477 -- data (Real a) => Ratio a = ...
478 -- But now I think that the laziness in checking class ops breaks
479 -- the loop, so no laziness needed
481 -- Read the argument types, but lazily to avoid faulting in
482 -- the component types unless they are really needed
483 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
484 ; lbl_names <- mappM lookupIfaceTop field_lbls
486 ; buildDataCon name is_infix {- Not infix -}
488 univ_tyvars ex_tyvars
492 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
497 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
498 ; ty <- tcIfaceType if_ty
503 %************************************************************************
507 %************************************************************************
510 tcIfaceInst :: IfaceInst -> IfL Instance
511 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
512 ifInstCls = cls, ifInstTys = mb_tcs,
514 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
515 tcIfaceExtId (LocalTop dfun_occ)
516 ; cls' <- lookupIfaceExt cls
517 ; mb_tcs' <- mapM do_tc mb_tcs
518 ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
520 do_tc Nothing = return Nothing
521 do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
525 %************************************************************************
529 %************************************************************************
531 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
532 are in the type environment. However, remember that typechecking a Rule may
533 (as a side effect) augment the type envt, and so we may need to iterate the process.
536 tcIfaceRule :: IfaceRule -> IfL CoreRule
537 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
538 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
540 = do { fn' <- lookupIfaceExt fn
541 ; ~(bndrs', args', rhs') <-
542 -- Typecheck the payload lazily, in the hope it'll never be looked at
543 forkM (ptext SLIT("Rule") <+> ftext name) $
544 bindIfaceBndrs bndrs $ \ bndrs' ->
545 do { args' <- mappM tcIfaceExpr args
546 ; rhs' <- tcIfaceExpr rhs
547 ; return (bndrs', args', rhs') }
548 ; mb_tcs <- mapM ifTopFreeName args
549 ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act,
550 ru_bndrs = bndrs', ru_args = args',
551 ru_rhs = rhs', ru_orph = orph,
553 ru_local = isLocalIfaceExtName fn }) }
555 -- This function *must* mirror exactly what Rules.topFreeName does
556 -- We could have stored the ru_rough field in the iface file
557 -- but that would be redundant, I think.
558 -- The only wrinkle is that we must not be deceived by
559 -- type syononyms at the top of a type arg. Since
560 -- we can't tell at this point, we are careful not
561 -- to write them out in coreRuleToIfaceRule
562 ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
563 ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
564 = do { n <- lookupIfaceTc tc
566 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
567 ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
569 ifTopFreeName other = return Nothing
573 %************************************************************************
577 %************************************************************************
580 tcIfaceType :: IfaceType -> IfL Type
581 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
582 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
583 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
584 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
585 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
586 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
588 tcIfaceTypes tys = mapM tcIfaceType tys
590 -----------------------------------------
591 tcIfacePredType :: IfacePredType -> IfL PredType
592 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
593 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
594 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
596 -----------------------------------------
597 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
598 tcIfaceCtxt sts = mappM tcIfacePredType sts
602 %************************************************************************
606 %************************************************************************
609 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
610 tcIfaceExpr (IfaceType ty)
611 = tcIfaceType ty `thenM` \ ty' ->
614 tcIfaceExpr (IfaceLcl name)
615 = tcIfaceLclId name `thenM` \ id ->
618 tcIfaceExpr (IfaceExt gbl)
619 = tcIfaceExtId gbl `thenM` \ id ->
622 tcIfaceExpr (IfaceLit lit)
625 tcIfaceExpr (IfaceFCall cc ty)
626 = tcIfaceType ty `thenM` \ ty' ->
627 newUnique `thenM` \ u ->
628 returnM (Var (mkFCallId u cc ty'))
630 tcIfaceExpr (IfaceTuple boxity args)
631 = mappM tcIfaceExpr args `thenM` \ args' ->
633 -- Put the missing type arguments back in
634 con_args = map (Type . exprType) args' ++ args'
636 returnM (mkApps (Var con_id) con_args)
639 con_id = dataConWorkId (tupleCon boxity arity)
642 tcIfaceExpr (IfaceLam bndr body)
643 = bindIfaceBndr bndr $ \ bndr' ->
644 tcIfaceExpr body `thenM` \ body' ->
645 returnM (Lam bndr' body')
647 tcIfaceExpr (IfaceApp fun arg)
648 = tcIfaceExpr fun `thenM` \ fun' ->
649 tcIfaceExpr arg `thenM` \ arg' ->
650 returnM (App fun' arg')
652 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
653 = tcIfaceExpr scrut `thenM` \ scrut' ->
654 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
656 scrut_ty = exprType scrut'
657 case_bndr' = mkLocalId case_bndr_name scrut_ty
658 tc_app = splitTyConApp scrut_ty
659 -- NB: Won't always succeed (polymoprhic case)
660 -- but won't be demanded in those cases
661 -- NB: not tcSplitTyConApp; we are looking at Core here
662 -- look through non-rec newtypes to find the tycon that
663 -- corresponds to the datacon in this case alternative
665 extendIfaceIdEnv [case_bndr'] $
666 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
667 tcIfaceType ty `thenM` \ ty' ->
668 returnM (Case scrut' case_bndr' ty' alts')
670 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
671 = tcIfaceExpr rhs `thenM` \ rhs' ->
672 bindIfaceId bndr $ \ bndr' ->
673 tcIfaceExpr body `thenM` \ body' ->
674 returnM (Let (NonRec bndr' rhs') body')
676 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
677 = bindIfaceIds bndrs $ \ bndrs' ->
678 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
679 tcIfaceExpr body `thenM` \ body' ->
680 returnM (Let (Rec (bndrs' `zip` rhss')) body')
682 (bndrs, rhss) = unzip pairs
684 tcIfaceExpr (IfaceCast expr co) = do
685 expr' <- tcIfaceExpr expr
686 co' <- tcIfaceType co
687 returnM (Cast expr' co')
689 tcIfaceExpr (IfaceNote note expr)
690 = tcIfaceExpr expr `thenM` \ expr' ->
692 IfaceInlineMe -> returnM (Note InlineMe expr')
693 IfaceSCC cc -> returnM (Note (SCC cc) expr')
694 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
696 -------------------------
697 tcIfaceAlt _ (IfaceDefault, names, rhs)
698 = ASSERT( null names )
699 tcIfaceExpr rhs `thenM` \ rhs' ->
700 returnM (DEFAULT, [], rhs')
702 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
703 = ASSERT( null names )
704 tcIfaceExpr rhs `thenM` \ rhs' ->
705 returnM (LitAlt lit, [], rhs')
707 -- A case alternative is made quite a bit more complicated
708 -- by the fact that we omit type annotations because we can
709 -- work them out. True enough, but its not that easy!
710 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
711 = do { let tycon_mod = nameModule (tyConName tycon)
712 ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
713 ; ASSERT2( con `elem` tyConDataCons tycon,
714 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
715 tcIfaceDataAlt con inst_tys arg_strs rhs }
717 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
718 = ASSERT( isTupleTyCon tycon )
719 do { let [data_con] = tyConDataCons tycon
720 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
722 tcIfaceDataAlt con inst_tys arg_strs rhs
723 = do { us <- newUniqueSupply
724 ; let uniqs = uniqsFromSupply us
725 ; let (ex_tvs, co_tvs, arg_ids)
726 = dataConRepFSInstPat arg_strs uniqs con inst_tys
727 all_tvs = ex_tvs ++ co_tvs
729 ; rhs' <- extendIfaceTyVarEnv all_tvs $
730 extendIfaceIdEnv arg_ids $
732 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
737 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
738 tcExtCoreBindings [] = return []
739 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
741 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
742 do_one (IfaceNonRec bndr rhs) thing_inside
743 = do { rhs' <- tcIfaceExpr rhs
744 ; bndr' <- newExtCoreBndr bndr
745 ; extendIfaceIdEnv [bndr'] $ do
746 { core_binds <- thing_inside
747 ; return (NonRec bndr' rhs' : core_binds) }}
749 do_one (IfaceRec pairs) thing_inside
750 = do { bndrs' <- mappM newExtCoreBndr bndrs
751 ; extendIfaceIdEnv bndrs' $ do
752 { rhss' <- mappM tcIfaceExpr rhss
753 ; core_binds <- thing_inside
754 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
756 (bndrs,rhss) = unzip pairs
760 %************************************************************************
764 %************************************************************************
767 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
768 tcIdInfo name ty NoInfo = return vanillaIdInfo
769 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
771 -- Set the CgInfo to something sensible but uninformative before
772 -- we start; default assumption is that it has CAFs
773 init_info = vanillaIdInfo
775 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
776 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
777 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
779 -- The next two are lazy, so they don't transitively suck stuff in
780 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
781 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
782 tcPrag info (HsUnfold expr)
783 = tcPragExpr name expr `thenM` \ maybe_expr' ->
785 -- maybe_expr' doesn't get looked at if the unfolding
786 -- is never inspected; so the typecheck doesn't even happen
787 unfold_info = case maybe_expr' of
788 Nothing -> noUnfolding
789 Just expr' -> mkTopUnfolding expr'
791 returnM (info `setUnfoldingInfoLazily` unfold_info)
795 tcWorkerInfo ty info wkr arity
796 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
798 -- We return without testing maybe_wkr_id, but as soon as info is
799 -- looked at we will test it. That's ok, because its outside the
800 -- knot; and there seems no big reason to further defer the
801 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
802 -- over the unfolding until it's actually used does seem worth while.)
803 ; us <- newUniqueSupply
805 ; returnM (case mb_wkr_id of
807 Just wkr_id -> add_wkr_info us wkr_id info) }
809 doc = text "Worker for" <+> ppr wkr
810 add_wkr_info us wkr_id info
811 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
812 `setWorkerInfo` HasWorker wkr_id arity
814 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
816 -- We are relying here on strictness info always appearing
817 -- before worker info, fingers crossed ....
818 strict_sig = case newStrictnessInfo info of
820 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
823 For unfoldings we try to do the job lazily, so that we never type check
824 an unfolding that isn't going to be looked at.
827 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
830 tcIfaceExpr expr `thenM` \ core_expr' ->
832 -- Check for type consistency in the unfolding
833 ifOptM Opt_DoCoreLinting (
834 get_in_scope_ids `thenM` \ in_scope ->
835 case lintUnfolding noSrcLoc in_scope core_expr' of
836 Nothing -> returnM ()
837 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
842 doc = text "Unfolding of" <+> ppr name
843 get_in_scope_ids -- Urgh; but just for linting
845 do { env <- getGblEnv
846 ; case if_rec_types env of {
847 Nothing -> return [] ;
848 Just (_, get_env) -> do
849 { type_env <- get_env
850 ; return (typeEnvIds type_env) }}}
855 %************************************************************************
857 Getting from Names to TyThings
859 %************************************************************************
862 tcIfaceGlobal :: Name -> IfL TyThing
864 | Just thing <- wiredInNameTyThing_maybe name
865 -- Wired-in things include TyCons, DataCons, and Ids
866 = do { loadWiredInHomeIface name; return thing }
867 -- Even though we are in an interface file, we want to make
868 -- sure its instances are loaded (imagine f :: Double -> Double)
869 -- and its RULES are loaded too
871 = do { (eps,hpt) <- getEpsAndHpt
873 ; case lookupType dflags hpt (eps_PTE eps) name of {
874 Just thing -> return thing ;
878 ; case if_rec_types env of {
879 Just (mod, get_type_env)
880 | nameIsLocalOrFrom mod name
881 -> do -- It's defined in the module being compiled
882 { type_env <- setLclEnv () get_type_env -- yuk
883 ; case lookupNameEnv type_env name of
884 Just thing -> return thing
885 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
886 (ppr name $$ ppr type_env) }
890 { mb_thing <- importDecl name -- It's imported; go get it
892 Failed err -> failIfM err
893 Succeeded thing -> return thing
896 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
897 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
898 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
899 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
900 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
901 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
902 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
903 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
904 ; thing <- tcIfaceGlobal name
905 ; return (check_tc (tyThingTyCon thing)) }
908 check_tc tc = case toIfaceTyCon (error "urk") tc of
910 other -> pprTrace "check_tc" (ppr tc) tc
914 -- we should be okay just returning Kind constructors without extra loading
915 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
916 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
917 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
918 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
919 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
921 -- Even though we are in an interface file, we want to make
922 -- sure the instances and RULES of this tycon are loaded
923 -- Imagine: f :: Double -> Double
924 tcWiredInTyCon :: TyCon -> IfL TyCon
925 tcWiredInTyCon tc = do { loadWiredInHomeIface (tyConName tc)
928 tcIfaceClass :: IfaceExtName -> IfL Class
929 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
930 ; thing <- tcIfaceGlobal name
931 ; return (tyThingClass thing) }
933 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
934 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
935 ; thing <- tcIfaceGlobal name
937 ADataCon dc -> return dc
938 other -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
940 tcIfaceExtId :: IfaceExtName -> IfL Id
941 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
942 ; thing <- tcIfaceGlobal name
945 other -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
948 %************************************************************************
952 %************************************************************************
955 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
956 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
957 = bindIfaceId bndr thing_inside
958 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
959 = bindIfaceTyVar bndr thing_inside
961 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
962 bindIfaceBndrs [] thing_inside = thing_inside []
963 bindIfaceBndrs (b:bs) thing_inside
964 = bindIfaceBndr b $ \ b' ->
965 bindIfaceBndrs bs $ \ bs' ->
966 thing_inside (b':bs')
968 -----------------------
969 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
970 bindIfaceId (occ, ty) thing_inside
971 = do { name <- newIfaceName (mkVarOccFS occ)
972 ; ty' <- tcIfaceType ty
973 ; let { id = mkLocalId name ty' }
974 ; extendIfaceIdEnv [id] (thing_inside id) }
976 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
977 bindIfaceIds bndrs thing_inside
978 = do { names <- newIfaceNames (map mkVarOccFS occs)
979 ; tys' <- mappM tcIfaceType tys
980 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
981 ; extendIfaceIdEnv ids (thing_inside ids) }
983 (occs,tys) = unzip bndrs
986 -----------------------
987 newExtCoreBndr :: IfaceIdBndr -> IfL Id
988 newExtCoreBndr (var, ty)
989 = do { mod <- getIfModule
990 ; name <- newGlobalBinder mod (mkVarOccFS var) Nothing noSrcLoc
991 ; ty' <- tcIfaceType ty
992 ; return (mkLocalId name ty') }
994 -----------------------
995 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
996 bindIfaceTyVar (occ,kind) thing_inside
997 = do { name <- newIfaceName (mkTyVarOcc occ)
998 ; tyvar <- mk_iface_tyvar name kind
999 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1001 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1002 bindIfaceTyVars bndrs thing_inside
1003 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1004 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1005 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1007 (occs,kinds) = unzip bndrs
1009 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1010 mk_iface_tyvar name ifKind = do { kind <- tcIfaceType ifKind
1011 ; return (mkTyVar name kind)