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, refineIfaceIdEnv,
21 newIfaceName, newIfaceNames, ifaceExportNames )
22 import BuildTyCl ( buildSynTyCon, buildAlgTyCon, buildDataCon, buildClass,
23 mkAbstractTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
25 import Type ( liftedTypeKind, splitTyConApp, mkTyConApp,
26 mkTyVarTys, ThetaType )
27 import TypeRep ( Type(..), PredType(..) )
28 import TyCon ( TyCon, tyConName )
29 import HscTypes ( ExternalPackageState(..),
30 TyThing(..), tyThingClass, tyThingTyCon,
31 ModIface(..), ModDetails(..), HomeModInfo(..),
32 emptyModDetails, lookupTypeEnv, lookupType, typeEnvIds )
33 import InstEnv ( Instance(..), mkImportedInstance )
34 import Unify ( coreRefineTys )
36 import CoreUtils ( exprType )
38 import CoreLint ( lintUnfolding )
39 import WorkWrap ( mkWrapper )
40 import Id ( Id, mkVanillaGlobal, mkLocalId )
41 import MkId ( mkFCallId )
42 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
43 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
44 setArityInfo, setInlinePragInfo, setCafInfo,
45 vanillaIdInfo, newStrictnessInfo )
46 import Class ( Class )
47 import TyCon ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
48 import DataCon ( DataCon, dataConWorkId, dataConTyVars, dataConInstArgTys, isVanillaDataCon )
49 import TysWiredIn ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
50 import Var ( TyVar, mkTyVar, tyVarKind )
51 import Name ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
52 wiredInNameTyThing_maybe, nameParent )
54 import OccName ( OccName )
55 import Module ( Module, lookupModuleEnv )
56 import UniqSupply ( initUs_ )
58 import ErrUtils ( Message )
59 import Maybes ( MaybeErr(..) )
60 import SrcLoc ( noSrcLoc )
61 import Util ( zipWithEqual, dropList, equalLength )
62 import DynFlags ( DynFlag(..), isOneShot )
71 An IfaceDecl is populated with RdrNames, and these are not renamed to
72 Names before typechecking, because there should be no scope errors etc.
74 -- For (b) consider: f = $(...h....)
75 -- where h is imported, and calls f via an hi-boot file.
76 -- This is bad! But it is not seen as a staging error, because h
77 -- is indeed imported. We don't want the type-checker to black-hole
78 -- when simplifying and compiling the splice!
80 -- Simple solution: discard any unfolding that mentions a variable
81 -- bound in this module (and hence not yet processed).
82 -- The discarding happens when forkM finds a type error.
84 %************************************************************************
86 %* tcImportDecl is the key function for "faulting in" *
89 %************************************************************************
91 The main idea is this. We are chugging along type-checking source code, and
92 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
93 it in the EPS type envt. So it
95 2 gets the decl for GHC.Base.map
96 3 typechecks it via tcIfaceDecl
97 4 and adds it to the type env in the EPS
99 Note that DURING STEP 4, we may find that map's type mentions a type
100 constructor that also
102 Notice that for imported things we read the current version from the EPS
103 mutable variable. This is important in situations like
105 where the code that e1 expands to might import some defns that
106 also turn out to be needed by the code that e2 expands to.
109 tcImportDecl :: Name -> TcM TyThing
110 -- Entry point for *source-code* uses of importDecl
112 | Just thing <- wiredInNameTyThing_maybe name
113 = do { initIfaceTcRn (loadWiredInHomeIface name)
116 = do { traceIf (text "tcImportDecl" <+> ppr name)
117 ; mb_thing <- initIfaceTcRn (importDecl name)
119 Succeeded thing -> return thing
120 Failed err -> failWithTc err }
122 checkWiredInTyCon :: TyCon -> TcM ()
123 -- Ensure that the home module of the TyCon (and hence its instances)
124 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
125 -- in which case this is a no-op.
127 | not (isWiredInName tc_name)
130 = do { mod <- getModule
131 ; if nameIsLocalOrFrom mod tc_name then
132 -- Don't look for (non-existent) Float.hi when
133 -- compiling Float.lhs, which mentions Float of course
135 else -- A bit yukky to call initIfaceTcRn here
136 initIfaceTcRn (loadWiredInHomeIface tc_name)
139 tc_name = tyConName tc
141 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
142 -- Get the TyThing for this Name from an interface file
143 -- It's not a wired-in thing -- the caller caught that
145 = ASSERT( not (isWiredInName name) )
148 -- Load the interface, which should populate the PTE
149 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
151 Failed err_msg -> return (Failed err_msg) ;
152 Succeeded iface -> do
154 -- Now look it up again; this time we should find it
156 ; case lookupTypeEnv (eps_PTE eps) name of
157 Just thing -> return (Succeeded thing)
158 Nothing -> return (Failed not_found_msg)
161 nd_doc = ptext SLIT("Need decl for") <+> ppr name
162 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+> ppr (nameParent name))
163 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
164 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
167 %************************************************************************
169 Type-checking a complete interface
171 %************************************************************************
173 Suppose we discover we don't need to recompile. Then we must type
174 check the old interface file. This is a bit different to the
175 incremental type checking we do as we suck in interface files. Instead
176 we do things similarly as when we are typechecking source decls: we
177 bring into scope the type envt for the interface all at once, using a
178 knot. Remember, the decls aren't necessarily in dependency order --
179 and even if they were, the type decls might be mutually recursive.
182 typecheckIface :: ModIface -- Get the decls from here
183 -> TcRnIf gbl lcl ModDetails
185 = initIfaceTc iface $ \ tc_env_var -> do
186 -- The tc_env_var is freshly allocated, private to
187 -- type-checking this particular interface
188 { -- Get the right set of decls and rules. If we are compiling without -O
189 -- we discard pragmas before typechecking, so that we don't "see"
190 -- information that we shouldn't. From a versioning point of view
191 -- It's not actually *wrong* to do so, but in fact GHCi is unable
192 -- to handle unboxed tuples, so it must not see unfoldings.
193 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
195 -- Load & typecheck the decls
196 ; decl_things <- loadDecls ignore_prags (mi_decls iface)
198 ; let type_env = mkNameEnv decl_things
199 ; writeMutVar tc_env_var type_env
201 -- Now do those rules and instances
202 ; let { rules | ignore_prags = []
203 | otherwise = mi_rules iface
204 ; dfuns = mi_insts iface
206 ; dfuns <- mapM tcIfaceInst dfuns
207 ; rules <- mapM tcIfaceRule rules
210 ; exports <- ifaceExportNames (mi_exports iface)
213 ; return (ModDetails { md_types = type_env,
216 md_exports = exports })
221 %************************************************************************
223 Type and class declarations
225 %************************************************************************
228 tcHiBootIface :: Module -> TcRn ModDetails
229 -- Load the hi-boot iface for the module being compiled,
230 -- if it indeed exists in the transitive closure of imports
231 -- Return the ModDetails, empty if no hi-boot iface
233 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
235 ; mode <- getGhciMode
236 ; if not (isOneShot mode)
237 -- In --make and interactive mode, if this module has an hs-boot file
238 -- we'll have compiled it already, and it'll be in the HPT
240 -- We check wheher the interface is a *boot* interface.
241 -- It can happen (when using GHC from Visual Studio) that we
242 -- compile a module in TypecheckOnly mode, with a stable,
243 -- fully-populated HPT. In that case the boot interface isn't there
244 -- (it's been replaced by the mother module) so we can't check it.
245 -- And that's fine, because if M's ModInfo is in the HPT, then
246 -- it's been compiled once, and we don't need to check the boot iface
247 then do { hpt <- getHpt
248 ; case lookupModuleEnv hpt mod of
249 Just info | mi_boot (hm_iface info)
250 -> return (hm_details info)
251 other -> return emptyModDetails }
254 -- OK, so we're in one-shot mode.
255 -- In that case, we're read all the direct imports by now,
256 -- so eps_is_boot will record if any of our imports mention us by
257 -- way of hi-boot file
259 ; case lookupModuleEnv (eps_is_boot eps) mod of {
260 Nothing -> return emptyModDetails ; -- The typical case
262 Just (_, False) -> failWithTc moduleLoop ;
263 -- Someone below us imported us!
264 -- This is a loop with no hi-boot in the way
266 Just (mod, True) -> -- There's a hi-boot interface below us
268 do { read_result <- findAndReadIface
269 True -- Explicit import?
273 ; case read_result of
274 Failed err -> failWithTc (elaborate err)
275 Succeeded (iface, _path) -> typecheckIface iface
278 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
279 <+> ptext SLIT("to compare against the Real Thing")
281 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
282 <+> ptext SLIT("depends on itself")
284 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
285 quotes (ppr mod) <> colon) 4 err
289 %************************************************************************
291 Type and class declarations
293 %************************************************************************
295 When typechecking a data type decl, we *lazily* (via forkM) typecheck
296 the constructor argument types. This is in the hope that we may never
297 poke on those argument types, and hence may never need to load the
298 interface files for types mentioned in the arg types.
301 data Foo.S = MkS Baz.T
302 Mabye we can get away without even loading the interface for Baz!
304 This is not just a performance thing. Suppose we have
305 data Foo.S = MkS Baz.T
306 data Baz.T = MkT Foo.S
307 (in different interface files, of course).
308 Now, first we load and typecheck Foo.S, and add it to the type envt.
309 If we do explore MkS's argument, we'll load and typecheck Baz.T.
310 If we explore MkT's argument we'll find Foo.S already in the envt.
312 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
313 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
314 which isn't done yet.
316 All very cunning. However, there is a rather subtle gotcha which bit
317 me when developing this stuff. When we typecheck the decl for S, we
318 extend the type envt with S, MkS, and all its implicit Ids. Suppose
319 (a bug, but it happened) that the list of implicit Ids depended in
320 turn on the constructor arg types. Then the following sequence of
322 * we build a thunk <t> for the constructor arg tys
323 * we build a thunk for the extended type environment (depends on <t>)
324 * we write the extended type envt into the global EPS mutvar
326 Now we look something up in the type envt
328 * which reads the global type envt out of the global EPS mutvar
329 * but that depends in turn on <t>
331 It's subtle, because, it'd work fine if we typechecked the constructor args
332 eagerly -- they don't need the extended type envt. They just get the extended
333 type envt by accident, because they look at it later.
335 What this means is that the implicitTyThings MUST NOT DEPEND on any of
340 tcIfaceDecl :: IfaceDecl -> IfL TyThing
342 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
343 = do { name <- lookupIfaceTop occ_name
344 ; ty <- tcIfaceType iface_type
345 ; info <- tcIdInfo name ty info
346 ; return (AnId (mkVanillaGlobal name ty info)) }
348 tcIfaceDecl (IfaceData {ifName = occ_name,
352 ifVrcs = arg_vrcs, ifRec = is_rec,
353 ifGeneric = want_generic })
354 = do { tc_name <- lookupIfaceTop occ_name
355 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
357 { tycon <- fixM ( \ tycon -> do
358 { stupid_theta <- tcIfaceCtxt ctxt
359 ; cons <- tcIfaceDataCons tycon tyvars rdr_cons
360 ; buildAlgTyCon tc_name tyvars stupid_theta
361 cons arg_vrcs is_rec want_generic
363 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
364 ; return (ATyCon tycon)
367 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
368 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
369 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
370 { tc_name <- lookupIfaceTop occ_name
371 ; rhs_ty <- tcIfaceType rdr_rhs_ty
372 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
375 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
376 ifFDs = rdr_fds, ifSigs = rdr_sigs,
377 ifVrcs = tc_vrcs, ifRec = tc_isrec })
378 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
379 { cls_name <- lookupIfaceTop occ_name
380 ; ctxt <- tcIfaceCtxt rdr_ctxt
381 ; sigs <- mappM tc_sig rdr_sigs
382 ; fds <- mappM tc_fd rdr_fds
383 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
384 ; return (AClass cls) }
386 tc_sig (IfaceClassOp occ dm rdr_ty)
387 = do { op_name <- lookupIfaceTop occ
388 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
389 -- Must be done lazily for just the same reason as the
390 -- context of a data decl: the type sig might mention the
391 -- class being defined
392 ; return (op_name, dm, op_ty) }
394 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
396 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
397 ; tvs2' <- mappM tcIfaceTyVar tvs2
398 ; return (tvs1', tvs2') }
400 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
401 = do { name <- lookupIfaceTop rdr_name
402 ; return (ATyCon (mkForeignTyCon name ext_name
403 liftedTypeKind 0 [])) }
405 tcIfaceDataCons tycon tc_tyvars if_cons
407 IfAbstractTyCon -> return mkAbstractTyConRhs
408 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
409 ; return (mkDataTyConRhs data_cons) }
410 IfNewTyCon con -> do { data_con <- tc_con_decl con
411 ; return (mkNewTyConRhs tycon data_con) }
413 tc_con_decl (IfVanillaCon { ifConOcc = occ, ifConInfix = is_infix, ifConArgTys = args,
414 ifConStricts = stricts, ifConFields = field_lbls})
415 = do { name <- lookupIfaceTop occ
416 -- Read the argument types, but lazily to avoid faulting in
417 -- the component types unless they are really needed
418 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
419 ; lbl_names <- mappM lookupIfaceTop field_lbls
420 ; buildDataCon name is_infix True {- Vanilla -}
422 tc_tyvars [] arg_tys tycon
423 (mkTyVarTys tc_tyvars) -- Vanilla => we know result tys
426 tc_con_decl (IfGadtCon { ifConTyVars = con_tvs,
427 ifConOcc = occ, ifConCtxt = ctxt,
428 ifConArgTys = args, ifConResTys = ress,
429 ifConStricts = stricts})
430 = bindIfaceTyVars con_tvs $ \ con_tyvars -> do
431 { name <- lookupIfaceTop occ
432 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
433 -- At one stage I thought that this context checking *had*
434 -- to be lazy, because of possible mutual recursion between the
435 -- type and the classe:
437 -- class Real a where { toRat :: a -> Ratio Integer }
438 -- data (Real a) => Ratio a = ...
439 -- But now I think that the laziness in checking class ops breaks
440 -- the loop, so no laziness needed
442 -- Read the argument types, but lazily to avoid faulting in
443 -- the component types unless they are really needed
444 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
445 ; res_tys <- forkM (mk_doc name) (mappM tcIfaceType ress)
447 ; buildDataCon name False {- Not infix -} False {- Not vanilla -}
448 stricts [{- No fields -}]
450 arg_tys tycon res_tys
452 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
456 %************************************************************************
460 %************************************************************************
463 tcIfaceInst :: IfaceInst -> IfL Instance
464 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
465 ifInstCls = cls, ifInstTys = mb_tcs,
467 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
468 tcIfaceExtId (LocalTop dfun_occ)
469 ; cls' <- lookupIfaceExt cls
470 ; mb_tcs' <- mapM do_tc mb_tcs
471 ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
473 do_tc Nothing = return Nothing
474 do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
478 %************************************************************************
482 %************************************************************************
484 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
485 are in the type environment. However, remember that typechecking a Rule may
486 (as a side effect) augment the type envt, and so we may need to iterate the process.
489 tcIfaceRule :: IfaceRule -> IfL CoreRule
490 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
491 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
493 = do { fn' <- lookupIfaceExt fn
494 ; ~(bndrs', args', rhs') <-
495 -- Typecheck the payload lazily, in the hope it'll never be looked at
496 forkM (ptext SLIT("Rule") <+> ftext name) $
497 bindIfaceBndrs bndrs $ \ bndrs' ->
498 do { args' <- mappM tcIfaceExpr args
499 ; rhs' <- tcIfaceExpr rhs
500 ; return (bndrs', args', rhs') }
501 ; mb_tcs <- mapM ifTopFreeName args
502 ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act,
503 ru_bndrs = bndrs', ru_args = args',
504 ru_rhs = rhs', ru_orph = orph,
506 ru_local = isLocalIfaceExtName fn }) }
508 -- This function *must* mirror exactly what Rules.topFreeName does
509 -- We could have stored the ru_rough field in the iface file
510 -- but that would be redundant, I think.
511 -- The only wrinkle is that we must not be deceived by
512 -- type syononyms at the top of a type arg. Since
513 -- we can't tell at this point, we are careful not
514 -- to write them out in coreRuleToIfaceRule
515 ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
516 ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
517 = do { n <- lookupIfaceTc tc
519 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
520 ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
522 ifTopFreeName other = return Nothing
526 %************************************************************************
530 %************************************************************************
533 tcIfaceType :: IfaceType -> IfL Type
534 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
535 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
536 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
537 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
538 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
539 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
541 tcIfaceTypes tys = mapM tcIfaceType tys
543 -----------------------------------------
544 tcIfacePredType :: IfacePredType -> IfL PredType
545 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
546 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
548 -----------------------------------------
549 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
550 tcIfaceCtxt sts = mappM tcIfacePredType sts
554 %************************************************************************
558 %************************************************************************
561 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
562 tcIfaceExpr (IfaceType ty)
563 = tcIfaceType ty `thenM` \ ty' ->
566 tcIfaceExpr (IfaceLcl name)
567 = tcIfaceLclId name `thenM` \ id ->
570 tcIfaceExpr (IfaceExt gbl)
571 = tcIfaceExtId gbl `thenM` \ id ->
574 tcIfaceExpr (IfaceLit lit)
577 tcIfaceExpr (IfaceFCall cc ty)
578 = tcIfaceType ty `thenM` \ ty' ->
579 newUnique `thenM` \ u ->
580 returnM (Var (mkFCallId u cc ty'))
582 tcIfaceExpr (IfaceTuple boxity args)
583 = mappM tcIfaceExpr args `thenM` \ args' ->
585 -- Put the missing type arguments back in
586 con_args = map (Type . exprType) args' ++ args'
588 returnM (mkApps (Var con_id) con_args)
591 con_id = dataConWorkId (tupleCon boxity arity)
594 tcIfaceExpr (IfaceLam bndr body)
595 = bindIfaceBndr bndr $ \ bndr' ->
596 tcIfaceExpr body `thenM` \ body' ->
597 returnM (Lam bndr' body')
599 tcIfaceExpr (IfaceApp fun arg)
600 = tcIfaceExpr fun `thenM` \ fun' ->
601 tcIfaceExpr arg `thenM` \ arg' ->
602 returnM (App fun' arg')
604 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
605 = tcIfaceExpr scrut `thenM` \ scrut' ->
606 newIfaceName case_bndr `thenM` \ case_bndr_name ->
608 scrut_ty = exprType scrut'
609 case_bndr' = mkLocalId case_bndr_name scrut_ty
610 tc_app = splitTyConApp scrut_ty
611 -- NB: Won't always succeed (polymoprhic case)
612 -- but won't be demanded in those cases
613 -- NB: not tcSplitTyConApp; we are looking at Core here
614 -- look through non-rec newtypes to find the tycon that
615 -- corresponds to the datacon in this case alternative
617 extendIfaceIdEnv [case_bndr'] $
618 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
619 tcIfaceType ty `thenM` \ ty' ->
620 returnM (Case scrut' case_bndr' ty' alts')
622 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
623 = tcIfaceExpr rhs `thenM` \ rhs' ->
624 bindIfaceId bndr $ \ bndr' ->
625 tcIfaceExpr body `thenM` \ body' ->
626 returnM (Let (NonRec bndr' rhs') body')
628 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
629 = bindIfaceIds bndrs $ \ bndrs' ->
630 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
631 tcIfaceExpr body `thenM` \ body' ->
632 returnM (Let (Rec (bndrs' `zip` rhss')) body')
634 (bndrs, rhss) = unzip pairs
636 tcIfaceExpr (IfaceNote note expr)
637 = tcIfaceExpr expr `thenM` \ expr' ->
639 IfaceCoerce to_ty -> tcIfaceType to_ty `thenM` \ to_ty' ->
640 returnM (Note (Coerce to_ty'
641 (exprType expr')) expr')
642 IfaceInlineCall -> returnM (Note InlineCall expr')
643 IfaceInlineMe -> returnM (Note InlineMe expr')
644 IfaceSCC cc -> returnM (Note (SCC cc) expr')
645 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
647 -------------------------
648 tcIfaceAlt _ (IfaceDefault, names, rhs)
649 = ASSERT( null names )
650 tcIfaceExpr rhs `thenM` \ rhs' ->
651 returnM (DEFAULT, [], rhs')
653 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
654 = ASSERT( null names )
655 tcIfaceExpr rhs `thenM` \ rhs' ->
656 returnM (LitAlt lit, [], rhs')
658 -- A case alternative is made quite a bit more complicated
659 -- by the fact that we omit type annotations because we can
660 -- work them out. True enough, but its not that easy!
661 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
662 = do { let tycon_mod = nameModule (tyConName tycon)
663 ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
664 ; ASSERT2( con `elem` tyConDataCons tycon,
665 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
667 if isVanillaDataCon con then
668 tcVanillaAlt con inst_tys arg_occs rhs
671 arg_names <- newIfaceNames arg_occs
672 ; let tyvars = [ mkTyVar name (tyVarKind tv)
673 | (name,tv) <- arg_names `zip` dataConTyVars con]
674 arg_tys = dataConInstArgTys con (mkTyVarTys tyvars)
675 id_names = dropList tyvars arg_names
676 arg_ids = ASSERT2( equalLength id_names arg_tys,
677 ppr (con, arg_names, rhs) $$ ppr tyvars $$ ppr arg_tys )
678 zipWith mkLocalId id_names arg_tys
680 Just refine = coreRefineTys con tyvars (mkTyConApp tycon inst_tys)
682 ; rhs' <- extendIfaceTyVarEnv tyvars $
683 extendIfaceIdEnv arg_ids $
684 refineIfaceIdEnv refine $
685 -- You might think that we don't need to refine the envt here,
686 -- but we do: \(x::a) -> case y of
687 -- MkT -> case x of { True -> ... }
688 -- In the "case x" we need to know x's type, because we use that
689 -- to find which module to look for "True" in. Sigh.
691 ; return (DataAlt con, tyvars ++ arg_ids, rhs') }}
693 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
694 = ASSERT( isTupleTyCon tycon )
695 do { let [data_con] = tyConDataCons tycon
696 ; tcVanillaAlt data_con inst_tys arg_occs rhs }
698 tcVanillaAlt data_con inst_tys arg_occs rhs
699 = do { arg_names <- newIfaceNames arg_occs
700 ; let arg_tys = dataConInstArgTys data_con inst_tys
701 ; let arg_ids = ASSERT2( equalLength arg_names arg_tys,
702 ppr data_con <+> ppr inst_tys <+> ppr arg_occs $$ ppr rhs )
703 zipWith mkLocalId arg_names arg_tys
704 ; rhs' <- extendIfaceIdEnv arg_ids (tcIfaceExpr rhs)
705 ; returnM (DataAlt data_con, arg_ids, rhs') }
710 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
711 tcExtCoreBindings [] = return []
712 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
714 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
715 do_one (IfaceNonRec bndr rhs) thing_inside
716 = do { rhs' <- tcIfaceExpr rhs
717 ; bndr' <- newExtCoreBndr bndr
718 ; extendIfaceIdEnv [bndr'] $ do
719 { core_binds <- thing_inside
720 ; return (NonRec bndr' rhs' : core_binds) }}
722 do_one (IfaceRec pairs) thing_inside
723 = do { bndrs' <- mappM newExtCoreBndr bndrs
724 ; extendIfaceIdEnv bndrs' $ do
725 { rhss' <- mappM tcIfaceExpr rhss
726 ; core_binds <- thing_inside
727 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
729 (bndrs,rhss) = unzip pairs
733 %************************************************************************
737 %************************************************************************
740 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
741 tcIdInfo name ty NoInfo = return vanillaIdInfo
742 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
744 -- Set the CgInfo to something sensible but uninformative before
745 -- we start; default assumption is that it has CAFs
746 init_info = vanillaIdInfo
748 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
749 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
750 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
752 -- The next two are lazy, so they don't transitively suck stuff in
753 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
754 tcPrag info (HsUnfold inline_prag expr)
755 = tcPragExpr name expr `thenM` \ maybe_expr' ->
757 -- maybe_expr' doesn't get looked at if the unfolding
758 -- is never inspected; so the typecheck doesn't even happen
759 unfold_info = case maybe_expr' of
760 Nothing -> noUnfolding
761 Just expr' -> mkTopUnfolding expr'
763 returnM (info `setUnfoldingInfoLazily` unfold_info
764 `setInlinePragInfo` inline_prag)
768 tcWorkerInfo ty info wkr arity
769 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
771 -- We return without testing maybe_wkr_id, but as soon as info is
772 -- looked at we will test it. That's ok, because its outside the
773 -- knot; and there seems no big reason to further defer the
774 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
775 -- over the unfolding until it's actually used does seem worth while.)
776 ; us <- newUniqueSupply
778 ; returnM (case mb_wkr_id of
780 Just wkr_id -> add_wkr_info us wkr_id info) }
782 doc = text "Worker for" <+> ppr wkr
783 add_wkr_info us wkr_id info
784 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
785 `setWorkerInfo` HasWorker wkr_id arity
787 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
789 -- We are relying here on strictness info always appearing
790 -- before worker info, fingers crossed ....
791 strict_sig = case newStrictnessInfo info of
793 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
796 For unfoldings we try to do the job lazily, so that we never type check
797 an unfolding that isn't going to be looked at.
800 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
803 tcIfaceExpr expr `thenM` \ core_expr' ->
805 -- Check for type consistency in the unfolding
806 ifOptM Opt_DoCoreLinting (
807 get_in_scope_ids `thenM` \ in_scope ->
808 case lintUnfolding noSrcLoc in_scope core_expr' of
809 Nothing -> returnM ()
810 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
815 doc = text "Unfolding of" <+> ppr name
816 get_in_scope_ids -- Urgh; but just for linting
818 do { env <- getGblEnv
819 ; case if_rec_types env of {
820 Nothing -> return [] ;
821 Just (_, get_env) -> do
822 { type_env <- get_env
823 ; return (typeEnvIds type_env) }}}
828 %************************************************************************
830 Getting from Names to TyThings
832 %************************************************************************
835 tcIfaceGlobal :: Name -> IfL TyThing
837 | Just thing <- wiredInNameTyThing_maybe name
838 -- Wired-in things include TyCons, DataCons, and Ids
839 = do { loadWiredInHomeIface name; return thing }
840 -- Even though we are in an interface file, we want to make
841 -- sure its instances are loaded (imagine f :: Double -> Double)
842 -- and its RULES are loaded too
844 = do { (eps,hpt) <- getEpsAndHpt
845 ; case lookupType hpt (eps_PTE eps) name of {
846 Just thing -> return thing ;
850 ; case if_rec_types env of {
851 Just (mod, get_type_env)
852 | nameIsLocalOrFrom mod name
853 -> do -- It's defined in the module being compiled
854 { type_env <- setLclEnv () get_type_env -- yuk
855 ; case lookupNameEnv type_env name of
856 Just thing -> return thing
857 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
858 (ppr name $$ ppr type_env) }
862 { mb_thing <- importDecl name -- It's imported; go get it
864 Failed err -> failIfM err
865 Succeeded thing -> return thing
868 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
869 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
870 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
871 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
872 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
873 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
874 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
875 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
876 ; thing <- tcIfaceGlobal name
877 ; return (check_tc (tyThingTyCon thing)) }
880 check_tc tc = case toIfaceTyCon (error "urk") tc of
882 other -> pprTrace "check_tc" (ppr tc) tc
887 -- Even though we are in an interface file, we want to make
888 -- sure the instances and RULES of this tycon are loaded
889 -- Imagine: f :: Double -> Double
890 tcWiredInTyCon :: TyCon -> IfL TyCon
891 tcWiredInTyCon tc = do { loadWiredInHomeIface (tyConName tc)
894 tcIfaceClass :: IfaceExtName -> IfL Class
895 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
896 ; thing <- tcIfaceGlobal name
897 ; return (tyThingClass thing) }
899 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
900 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
901 ; thing <- tcIfaceGlobal name
903 ADataCon dc -> return dc
904 other -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
906 tcIfaceExtId :: IfaceExtName -> IfL Id
907 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
908 ; thing <- tcIfaceGlobal name
911 other -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
914 %************************************************************************
918 %************************************************************************
921 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
922 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
923 = bindIfaceId bndr thing_inside
924 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
925 = bindIfaceTyVar bndr thing_inside
927 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
928 bindIfaceBndrs [] thing_inside = thing_inside []
929 bindIfaceBndrs (b:bs) thing_inside
930 = bindIfaceBndr b $ \ b' ->
931 bindIfaceBndrs bs $ \ bs' ->
932 thing_inside (b':bs')
934 -----------------------
935 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
936 bindIfaceId (occ, ty) thing_inside
937 = do { name <- newIfaceName occ
938 ; ty' <- tcIfaceType ty
939 ; let { id = mkLocalId name ty' }
940 ; extendIfaceIdEnv [id] (thing_inside id) }
942 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
943 bindIfaceIds bndrs thing_inside
944 = do { names <- newIfaceNames occs
945 ; tys' <- mappM tcIfaceType tys
946 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
947 ; extendIfaceIdEnv ids (thing_inside ids) }
949 (occs,tys) = unzip bndrs
952 -----------------------
953 newExtCoreBndr :: (OccName, IfaceType) -> IfL Id
954 newExtCoreBndr (occ, ty)
955 = do { mod <- getIfModule
956 ; name <- newGlobalBinder mod occ Nothing noSrcLoc
957 ; ty' <- tcIfaceType ty
958 ; return (mkLocalId name ty') }
960 -----------------------
961 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
962 bindIfaceTyVar (occ,kind) thing_inside
963 = do { name <- newIfaceName occ
964 ; let tyvar = mk_iface_tyvar name kind
965 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
967 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
968 bindIfaceTyVars bndrs thing_inside
969 = do { names <- newIfaceNames occs
970 ; let tyvars = zipWith mk_iface_tyvar names kinds
971 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
973 (occs,kinds) = unzip bndrs
975 mk_iface_tyvar name kind = mkTyVar name kind