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, buildClass,
23 mkAbstractTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
25 import Type ( liftedTypeKind, splitTyConApp, mkTyConApp,
26 liftedTypeKindTyCon, unliftedTypeKindTyCon,
27 openTypeKindTyCon, argTypeKindTyCon,
29 mkTyVarTys, ThetaType )
30 import TypeRep ( Type(..), PredType(..) )
31 import TyCon ( TyCon, tyConName )
32 import HscTypes ( ExternalPackageState(..),
33 TyThing(..), tyThingClass, tyThingTyCon,
34 ModIface(..), ModDetails(..), HomeModInfo(..),
35 emptyModDetails, lookupTypeEnv, lookupType, typeEnvIds )
36 import InstEnv ( Instance(..), mkImportedInstance )
38 import CoreUtils ( exprType )
40 import CoreLint ( lintUnfolding )
41 import WorkWrap ( mkWrapper )
42 import Id ( Id, mkVanillaGlobal, mkLocalId )
43 import MkId ( mkFCallId )
44 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
45 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
46 setArityInfo, setInlinePragInfo, setCafInfo,
47 vanillaIdInfo, newStrictnessInfo )
48 import Class ( Class )
49 import TyCon ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
50 import DataCon ( DataCon, dataConWorkId, dataConExTyVars, dataConInstArgTys )
51 import TysWiredIn ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
52 import Var ( TyVar, mkTyVar, tyVarKind )
53 import Name ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
54 nameOccName, wiredInNameTyThing_maybe )
56 import OccName ( OccName, mkVarOccFS, mkTyVarOccoccNameSpace, pprNameSpace )
57 import FastString ( FastString )
58 import Module ( Module, moduleName )
59 import UniqFM ( lookupUFM )
60 import UniqSupply ( initUs_ )
62 import ErrUtils ( Message )
63 import Maybes ( MaybeErr(..) )
64 import SrcLoc ( noSrcLoc )
65 import Util ( zipWithEqual, equalLength, splitAtList )
66 import DynFlags ( DynFlag(..), isOneShot )
76 An IfaceDecl is populated with RdrNames, and these are not renamed to
77 Names before typechecking, because there should be no scope errors etc.
79 -- For (b) consider: f = $(...h....)
80 -- where h is imported, and calls f via an hi-boot file.
81 -- This is bad! But it is not seen as a staging error, because h
82 -- is indeed imported. We don't want the type-checker to black-hole
83 -- when simplifying and compiling the splice!
85 -- Simple solution: discard any unfolding that mentions a variable
86 -- bound in this module (and hence not yet processed).
87 -- The discarding happens when forkM finds a type error.
89 %************************************************************************
91 %* tcImportDecl is the key function for "faulting in" *
94 %************************************************************************
96 The main idea is this. We are chugging along type-checking source code, and
97 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
98 it in the EPS type envt. So it
100 2 gets the decl for GHC.Base.map
101 3 typechecks it via tcIfaceDecl
102 4 and adds it to the type env in the EPS
104 Note that DURING STEP 4, we may find that map's type mentions a type
105 constructor that also
107 Notice that for imported things we read the current version from the EPS
108 mutable variable. This is important in situations like
110 where the code that e1 expands to might import some defns that
111 also turn out to be needed by the code that e2 expands to.
114 tcImportDecl :: Name -> TcM TyThing
115 -- Entry point for *source-code* uses of importDecl
117 | Just thing <- wiredInNameTyThing_maybe name
118 = do { initIfaceTcRn (loadWiredInHomeIface name)
121 = do { traceIf (text "tcImportDecl" <+> ppr name)
122 ; mb_thing <- initIfaceTcRn (importDecl name)
124 Succeeded thing -> return thing
125 Failed err -> failWithTc err }
127 checkWiredInTyCon :: TyCon -> TcM ()
128 -- Ensure that the home module of the TyCon (and hence its instances)
129 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
130 -- in which case this is a no-op.
132 | not (isWiredInName tc_name)
135 = do { mod <- getModule
136 ; if nameIsLocalOrFrom mod tc_name then
137 -- Don't look for (non-existent) Float.hi when
138 -- compiling Float.lhs, which mentions Float of course
140 else -- A bit yukky to call initIfaceTcRn here
141 initIfaceTcRn (loadWiredInHomeIface tc_name)
144 tc_name = tyConName tc
146 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
147 -- Get the TyThing for this Name from an interface file
148 -- It's not a wired-in thing -- the caller caught that
150 = ASSERT( not (isWiredInName name) )
153 -- Load the interface, which should populate the PTE
154 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
156 Failed err_msg -> return (Failed err_msg) ;
157 Succeeded iface -> do
159 -- Now look it up again; this time we should find it
161 ; case lookupTypeEnv (eps_PTE eps) name of
162 Just thing -> return (Succeeded thing)
163 Nothing -> return (Failed not_found_msg)
166 nd_doc = ptext SLIT("Need decl for") <+> ppr name
167 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
168 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
169 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
170 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
173 %************************************************************************
175 Type-checking a complete interface
177 %************************************************************************
179 Suppose we discover we don't need to recompile. Then we must type
180 check the old interface file. This is a bit different to the
181 incremental type checking we do as we suck in interface files. Instead
182 we do things similarly as when we are typechecking source decls: we
183 bring into scope the type envt for the interface all at once, using a
184 knot. Remember, the decls aren't necessarily in dependency order --
185 and even if they were, the type decls might be mutually recursive.
188 typecheckIface :: ModIface -- Get the decls from here
189 -> TcRnIf gbl lcl ModDetails
191 = initIfaceTc iface $ \ tc_env_var -> do
192 -- The tc_env_var is freshly allocated, private to
193 -- type-checking this particular interface
194 { -- Get the right set of decls and rules. If we are compiling without -O
195 -- we discard pragmas before typechecking, so that we don't "see"
196 -- information that we shouldn't. From a versioning point of view
197 -- It's not actually *wrong* to do so, but in fact GHCi is unable
198 -- to handle unboxed tuples, so it must not see unfoldings.
199 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
201 -- Load & typecheck the decls
202 ; decl_things <- loadDecls ignore_prags (mi_decls iface)
204 ; let type_env = mkNameEnv decl_things
205 ; writeMutVar tc_env_var type_env
207 -- Now do those rules and instances
208 ; let { rules | ignore_prags = []
209 | otherwise = mi_rules iface
210 ; dfuns = mi_insts iface
212 ; dfuns <- mapM tcIfaceInst dfuns
213 ; rules <- mapM tcIfaceRule rules
216 ; exports <- ifaceExportNames (mi_exports iface)
219 ; return (ModDetails { md_types = type_env,
222 md_exports = exports })
227 %************************************************************************
229 Type and class declarations
231 %************************************************************************
234 tcHiBootIface :: Module -> TcRn ModDetails
235 -- Load the hi-boot iface for the module being compiled,
236 -- if it indeed exists in the transitive closure of imports
237 -- Return the ModDetails, empty if no hi-boot iface
239 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
242 ; if not (isOneShot mode)
243 -- In --make and interactive mode, if this module has an hs-boot file
244 -- we'll have compiled it already, and it'll be in the HPT
246 -- We check wheher the interface is a *boot* interface.
247 -- It can happen (when using GHC from Visual Studio) that we
248 -- compile a module in TypecheckOnly mode, with a stable,
249 -- fully-populated HPT. In that case the boot interface isn't there
250 -- (it's been replaced by the mother module) so we can't check it.
251 -- And that's fine, because if M's ModInfo is in the HPT, then
252 -- it's been compiled once, and we don't need to check the boot iface
253 then do { hpt <- getHpt
254 ; case lookupUFM hpt (moduleName mod) of
255 Just info | mi_boot (hm_iface info)
256 -> return (hm_details info)
257 other -> return emptyModDetails }
260 -- OK, so we're in one-shot mode.
261 -- In that case, we're read all the direct imports by now,
262 -- so eps_is_boot will record if any of our imports mention us by
263 -- way of hi-boot file
265 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
266 Nothing -> return emptyModDetails ; -- The typical case
268 Just (_, False) -> failWithTc moduleLoop ;
269 -- Someone below us imported us!
270 -- This is a loop with no hi-boot in the way
272 Just (_mod, True) -> -- There's a hi-boot interface below us
274 do { read_result <- findAndReadIface
278 ; case read_result of
279 Failed err -> failWithTc (elaborate err)
280 Succeeded (iface, _path) -> typecheckIface iface
283 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
284 <+> ptext SLIT("to compare against the Real Thing")
286 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
287 <+> ptext SLIT("depends on itself")
289 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
290 quotes (ppr mod) <> colon) 4 err
294 %************************************************************************
296 Type and class declarations
298 %************************************************************************
300 When typechecking a data type decl, we *lazily* (via forkM) typecheck
301 the constructor argument types. This is in the hope that we may never
302 poke on those argument types, and hence may never need to load the
303 interface files for types mentioned in the arg types.
306 data Foo.S = MkS Baz.T
307 Mabye we can get away without even loading the interface for Baz!
309 This is not just a performance thing. Suppose we have
310 data Foo.S = MkS Baz.T
311 data Baz.T = MkT Foo.S
312 (in different interface files, of course).
313 Now, first we load and typecheck Foo.S, and add it to the type envt.
314 If we do explore MkS's argument, we'll load and typecheck Baz.T.
315 If we explore MkT's argument we'll find Foo.S already in the envt.
317 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
318 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
319 which isn't done yet.
321 All very cunning. However, there is a rather subtle gotcha which bit
322 me when developing this stuff. When we typecheck the decl for S, we
323 extend the type envt with S, MkS, and all its implicit Ids. Suppose
324 (a bug, but it happened) that the list of implicit Ids depended in
325 turn on the constructor arg types. Then the following sequence of
327 * we build a thunk <t> for the constructor arg tys
328 * we build a thunk for the extended type environment (depends on <t>)
329 * we write the extended type envt into the global EPS mutvar
331 Now we look something up in the type envt
333 * which reads the global type envt out of the global EPS mutvar
334 * but that depends in turn on <t>
336 It's subtle, because, it'd work fine if we typechecked the constructor args
337 eagerly -- they don't need the extended type envt. They just get the extended
338 type envt by accident, because they look at it later.
340 What this means is that the implicitTyThings MUST NOT DEPEND on any of
345 tcIfaceDecl :: IfaceDecl -> IfL TyThing
347 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
348 = do { name <- lookupIfaceTop occ_name
349 ; ty <- tcIfaceType iface_type
350 ; info <- tcIdInfo name ty info
351 ; return (AnId (mkVanillaGlobal name ty info)) }
353 tcIfaceDecl (IfaceData {ifName = occ_name,
355 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
357 ifVrcs = arg_vrcs, ifRec = is_rec,
358 ifGeneric = want_generic })
359 = do { tc_name <- lookupIfaceTop occ_name
360 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
362 { tycon <- fixM ( \ tycon -> do
363 { stupid_theta <- tcIfaceCtxt ctxt
364 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
365 ; buildAlgTyCon tc_name tyvars stupid_theta
366 cons arg_vrcs is_rec want_generic gadt_syn
368 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
369 ; return (ATyCon tycon)
372 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
373 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
374 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
375 { tc_name <- lookupIfaceTop occ_name
376 ; rhs_ty <- tcIfaceType rdr_rhs_ty
377 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
380 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
381 ifFDs = rdr_fds, ifSigs = rdr_sigs,
382 ifVrcs = tc_vrcs, ifRec = tc_isrec })
383 -- ToDo: in hs-boot files we should really treat abstract classes specially,
384 -- as we do abstract tycons
385 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
386 { cls_name <- lookupIfaceTop occ_name
387 ; ctxt <- tcIfaceCtxt rdr_ctxt
388 ; sigs <- mappM tc_sig rdr_sigs
389 ; fds <- mappM tc_fd rdr_fds
390 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
391 ; return (AClass cls) }
393 tc_sig (IfaceClassOp occ dm rdr_ty)
394 = do { op_name <- lookupIfaceTop occ
395 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
396 -- Must be done lazily for just the same reason as the
397 -- context of a data decl: the type sig might mention the
398 -- class being defined
399 ; return (op_name, dm, op_ty) }
401 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
403 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
404 ; tvs2' <- mappM tcIfaceTyVar tvs2
405 ; return (tvs1', tvs2') }
407 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
408 = do { name <- lookupIfaceTop rdr_name
409 ; return (ATyCon (mkForeignTyCon name ext_name
410 liftedTypeKind 0 [])) }
412 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
414 IfAbstractTyCon -> return mkAbstractTyConRhs
415 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
416 ; return (mkDataTyConRhs data_cons) }
417 IfNewTyCon con -> do { data_con <- tc_con_decl con
418 ; mkNewTyConRhs tycon_name tycon data_con }
420 tc_con_decl (IfCon { ifConInfix = is_infix,
421 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
422 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
423 ifConArgTys = args, ifConFields = field_lbls,
424 ifConStricts = stricts})
425 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
426 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
427 { name <- lookupIfaceTop occ
428 ; eq_spec <- tcIfaceEqSpec spec
429 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
430 -- At one stage I thought that this context checking *had*
431 -- to be lazy, because of possible mutual recursion between the
432 -- type and the classe:
434 -- class Real a where { toRat :: a -> Ratio Integer }
435 -- data (Real a) => Ratio a = ...
436 -- But now I think that the laziness in checking class ops breaks
437 -- the loop, so no laziness needed
439 -- Read the argument types, but lazily to avoid faulting in
440 -- the component types unless they are really needed
441 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
442 ; lbl_names <- mappM lookupIfaceTop field_lbls
444 ; buildDataCon name is_infix {- Not infix -}
446 univ_tyvars ex_tyvars
450 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
455 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
456 ; ty <- tcIfaceType if_ty
461 %************************************************************************
465 %************************************************************************
468 tcIfaceInst :: IfaceInst -> IfL Instance
469 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
470 ifInstCls = cls, ifInstTys = mb_tcs,
472 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
473 tcIfaceExtId (LocalTop dfun_occ)
474 ; cls' <- lookupIfaceExt cls
475 ; mb_tcs' <- mapM do_tc mb_tcs
476 ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
478 do_tc Nothing = return Nothing
479 do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
483 %************************************************************************
487 %************************************************************************
489 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
490 are in the type environment. However, remember that typechecking a Rule may
491 (as a side effect) augment the type envt, and so we may need to iterate the process.
494 tcIfaceRule :: IfaceRule -> IfL CoreRule
495 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
496 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
498 = do { fn' <- lookupIfaceExt fn
499 ; ~(bndrs', args', rhs') <-
500 -- Typecheck the payload lazily, in the hope it'll never be looked at
501 forkM (ptext SLIT("Rule") <+> ftext name) $
502 bindIfaceBndrs bndrs $ \ bndrs' ->
503 do { args' <- mappM tcIfaceExpr args
504 ; rhs' <- tcIfaceExpr rhs
505 ; return (bndrs', args', rhs') }
506 ; mb_tcs <- mapM ifTopFreeName args
507 ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act,
508 ru_bndrs = bndrs', ru_args = args',
509 ru_rhs = rhs', ru_orph = orph,
511 ru_local = isLocalIfaceExtName fn }) }
513 -- This function *must* mirror exactly what Rules.topFreeName does
514 -- We could have stored the ru_rough field in the iface file
515 -- but that would be redundant, I think.
516 -- The only wrinkle is that we must not be deceived by
517 -- type syononyms at the top of a type arg. Since
518 -- we can't tell at this point, we are careful not
519 -- to write them out in coreRuleToIfaceRule
520 ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
521 ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
522 = do { n <- lookupIfaceTc tc
524 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
525 ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
527 ifTopFreeName other = return Nothing
531 %************************************************************************
535 %************************************************************************
538 tcIfaceType :: IfaceType -> IfL Type
539 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
540 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
541 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
542 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
543 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
544 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
546 tcIfaceTypes tys = mapM tcIfaceType tys
548 -----------------------------------------
549 tcIfacePredType :: IfacePredType -> IfL PredType
550 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
551 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
552 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
554 -----------------------------------------
555 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
556 tcIfaceCtxt sts = mappM tcIfacePredType sts
560 %************************************************************************
564 %************************************************************************
567 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
568 tcIfaceExpr (IfaceType ty)
569 = tcIfaceType ty `thenM` \ ty' ->
572 tcIfaceExpr (IfaceLcl name)
573 = tcIfaceLclId name `thenM` \ id ->
576 tcIfaceExpr (IfaceExt gbl)
577 = tcIfaceExtId gbl `thenM` \ id ->
580 tcIfaceExpr (IfaceLit lit)
583 tcIfaceExpr (IfaceFCall cc ty)
584 = tcIfaceType ty `thenM` \ ty' ->
585 newUnique `thenM` \ u ->
586 returnM (Var (mkFCallId u cc ty'))
588 tcIfaceExpr (IfaceTuple boxity args)
589 = mappM tcIfaceExpr args `thenM` \ args' ->
591 -- Put the missing type arguments back in
592 con_args = map (Type . exprType) args' ++ args'
594 returnM (mkApps (Var con_id) con_args)
597 con_id = dataConWorkId (tupleCon boxity arity)
600 tcIfaceExpr (IfaceLam bndr body)
601 = bindIfaceBndr bndr $ \ bndr' ->
602 tcIfaceExpr body `thenM` \ body' ->
603 returnM (Lam bndr' body')
605 tcIfaceExpr (IfaceApp fun arg)
606 = tcIfaceExpr fun `thenM` \ fun' ->
607 tcIfaceExpr arg `thenM` \ arg' ->
608 returnM (App fun' arg')
610 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
611 = tcIfaceExpr scrut `thenM` \ scrut' ->
612 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
614 scrut_ty = exprType scrut'
615 case_bndr' = mkLocalId case_bndr_name scrut_ty
616 tc_app = splitTyConApp scrut_ty
617 -- NB: Won't always succeed (polymoprhic case)
618 -- but won't be demanded in those cases
619 -- NB: not tcSplitTyConApp; we are looking at Core here
620 -- look through non-rec newtypes to find the tycon that
621 -- corresponds to the datacon in this case alternative
623 extendIfaceIdEnv [case_bndr'] $
624 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
625 tcIfaceType ty `thenM` \ ty' ->
626 returnM (Case scrut' case_bndr' ty' alts')
628 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
629 = tcIfaceExpr rhs `thenM` \ rhs' ->
630 bindIfaceId bndr $ \ bndr' ->
631 tcIfaceExpr body `thenM` \ body' ->
632 returnM (Let (NonRec bndr' rhs') body')
634 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
635 = bindIfaceIds bndrs $ \ bndrs' ->
636 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
637 tcIfaceExpr body `thenM` \ body' ->
638 returnM (Let (Rec (bndrs' `zip` rhss')) body')
640 (bndrs, rhss) = unzip pairs
642 tcIfaceExpr (IfaceCast expr co) = do
643 expr' <- tcIfaceExpr expr
644 co' <- tcIfaceType co
645 returnM (Cast expr' co')
647 tcIfaceExpr (IfaceNote note expr)
648 = tcIfaceExpr expr `thenM` \ expr' ->
650 IfaceInlineMe -> returnM (Note InlineMe expr')
651 IfaceSCC cc -> returnM (Note (SCC cc) expr')
652 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
654 -------------------------
655 tcIfaceAlt _ (IfaceDefault, names, rhs)
656 = ASSERT( null names )
657 tcIfaceExpr rhs `thenM` \ rhs' ->
658 returnM (DEFAULT, [], rhs')
660 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
661 = ASSERT( null names )
662 tcIfaceExpr rhs `thenM` \ rhs' ->
663 returnM (LitAlt lit, [], rhs')
665 -- A case alternative is made quite a bit more complicated
666 -- by the fact that we omit type annotations because we can
667 -- work them out. True enough, but its not that easy!
668 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
669 = do { let tycon_mod = nameModule (tyConName tycon)
670 ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
671 ; ASSERT2( con `elem` tyConDataCons tycon,
672 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
673 tcIfaceDataAlt con inst_tys arg_strs rhs }
675 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
676 = ASSERT( isTupleTyCon tycon )
677 do { let [data_con] = tyConDataCons tycon
678 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
680 tcIfaceDataAlt con inst_tys arg_strs rhs
681 = do { arg_names <- newIfaceNames (map mkVarOccFS arg_strs)
682 ; let (tyvar_strs, id_strs) = splitAtList (dataConTyVars con) arg_strs
683 ; tyvar_names <- mapM (newIfaceName . mkTyVarOcc) tyvar_strs
684 ; id_names <- mapM (newIfaceName . mkVarOccFS) id_strs
685 ; let ex_tvs = [ mkTyVar name (tyVarKind tv)
686 | (name,tv) <- tyvar_names `zip` dataConExTyVars con ]
687 arg_tys = dataConInstArgTys con (inst_tys ++ mkTyVarTys ex_tvs)
688 arg_ids = ASSERT2( equalLength id_names arg_tys,
689 ppr (con, tyvar_names++id_names, rhs) $$ ppr ex_tvs $$ ppr arg_tys )
690 zipWith mkLocalId id_names arg_tys
692 ; rhs' <- extendIfaceTyVarEnv ex_tvs $
693 extendIfaceIdEnv arg_ids $
695 ; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
700 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
701 tcExtCoreBindings [] = return []
702 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
704 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
705 do_one (IfaceNonRec bndr rhs) thing_inside
706 = do { rhs' <- tcIfaceExpr rhs
707 ; bndr' <- newExtCoreBndr bndr
708 ; extendIfaceIdEnv [bndr'] $ do
709 { core_binds <- thing_inside
710 ; return (NonRec bndr' rhs' : core_binds) }}
712 do_one (IfaceRec pairs) thing_inside
713 = do { bndrs' <- mappM newExtCoreBndr bndrs
714 ; extendIfaceIdEnv bndrs' $ do
715 { rhss' <- mappM tcIfaceExpr rhss
716 ; core_binds <- thing_inside
717 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
719 (bndrs,rhss) = unzip pairs
723 %************************************************************************
727 %************************************************************************
730 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
731 tcIdInfo name ty NoInfo = return vanillaIdInfo
732 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
734 -- Set the CgInfo to something sensible but uninformative before
735 -- we start; default assumption is that it has CAFs
736 init_info = vanillaIdInfo
738 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
739 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
740 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
742 -- The next two are lazy, so they don't transitively suck stuff in
743 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
744 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
745 tcPrag info (HsUnfold expr)
746 = tcPragExpr name expr `thenM` \ maybe_expr' ->
748 -- maybe_expr' doesn't get looked at if the unfolding
749 -- is never inspected; so the typecheck doesn't even happen
750 unfold_info = case maybe_expr' of
751 Nothing -> noUnfolding
752 Just expr' -> mkTopUnfolding expr'
754 returnM (info `setUnfoldingInfoLazily` unfold_info)
758 tcWorkerInfo ty info wkr arity
759 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
761 -- We return without testing maybe_wkr_id, but as soon as info is
762 -- looked at we will test it. That's ok, because its outside the
763 -- knot; and there seems no big reason to further defer the
764 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
765 -- over the unfolding until it's actually used does seem worth while.)
766 ; us <- newUniqueSupply
768 ; returnM (case mb_wkr_id of
770 Just wkr_id -> add_wkr_info us wkr_id info) }
772 doc = text "Worker for" <+> ppr wkr
773 add_wkr_info us wkr_id info
774 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
775 `setWorkerInfo` HasWorker wkr_id arity
777 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
779 -- We are relying here on strictness info always appearing
780 -- before worker info, fingers crossed ....
781 strict_sig = case newStrictnessInfo info of
783 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
786 For unfoldings we try to do the job lazily, so that we never type check
787 an unfolding that isn't going to be looked at.
790 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
793 tcIfaceExpr expr `thenM` \ core_expr' ->
795 -- Check for type consistency in the unfolding
796 ifOptM Opt_DoCoreLinting (
797 get_in_scope_ids `thenM` \ in_scope ->
798 case lintUnfolding noSrcLoc in_scope core_expr' of
799 Nothing -> returnM ()
800 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
805 doc = text "Unfolding of" <+> ppr name
806 get_in_scope_ids -- Urgh; but just for linting
808 do { env <- getGblEnv
809 ; case if_rec_types env of {
810 Nothing -> return [] ;
811 Just (_, get_env) -> do
812 { type_env <- get_env
813 ; return (typeEnvIds type_env) }}}
818 %************************************************************************
820 Getting from Names to TyThings
822 %************************************************************************
825 tcIfaceGlobal :: Name -> IfL TyThing
827 | Just thing <- wiredInNameTyThing_maybe name
828 -- Wired-in things include TyCons, DataCons, and Ids
829 = do { loadWiredInHomeIface name; return thing }
830 -- Even though we are in an interface file, we want to make
831 -- sure its instances are loaded (imagine f :: Double -> Double)
832 -- and its RULES are loaded too
834 = do { (eps,hpt) <- getEpsAndHpt
836 ; case lookupType dflags hpt (eps_PTE eps) name of {
837 Just thing -> return thing ;
841 ; case if_rec_types env of {
842 Just (mod, get_type_env)
843 | nameIsLocalOrFrom mod name
844 -> do -- It's defined in the module being compiled
845 { type_env <- setLclEnv () get_type_env -- yuk
846 ; case lookupNameEnv type_env name of
847 Just thing -> return thing
848 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
849 (ppr name $$ ppr type_env) }
853 { mb_thing <- importDecl name -- It's imported; go get it
855 Failed err -> failIfM err
856 Succeeded thing -> return thing
859 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
860 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
861 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
862 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
863 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
864 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
865 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
866 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
867 ; thing <- tcIfaceGlobal name
868 ; return (check_tc (tyThingTyCon thing)) }
871 check_tc tc = case toIfaceTyCon (error "urk") tc of
873 other -> pprTrace "check_tc" (ppr tc) tc
877 -- we should be okay just returning Kind constructors without extra loading
878 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
879 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
880 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
881 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
882 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
884 -- Even though we are in an interface file, we want to make
885 -- sure the instances and RULES of this tycon are loaded
886 -- Imagine: f :: Double -> Double
887 tcWiredInTyCon :: TyCon -> IfL TyCon
888 tcWiredInTyCon tc = do { loadWiredInHomeIface (tyConName tc)
891 tcIfaceClass :: IfaceExtName -> IfL Class
892 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
893 ; thing <- tcIfaceGlobal name
894 ; return (tyThingClass thing) }
896 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
897 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
898 ; thing <- tcIfaceGlobal name
900 ADataCon dc -> return dc
901 other -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
903 tcIfaceExtId :: IfaceExtName -> IfL Id
904 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
905 ; thing <- tcIfaceGlobal name
908 other -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
911 %************************************************************************
915 %************************************************************************
918 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
919 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
920 = bindIfaceId bndr thing_inside
921 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
922 = bindIfaceTyVar bndr thing_inside
924 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
925 bindIfaceBndrs [] thing_inside = thing_inside []
926 bindIfaceBndrs (b:bs) thing_inside
927 = bindIfaceBndr b $ \ b' ->
928 bindIfaceBndrs bs $ \ bs' ->
929 thing_inside (b':bs')
931 -----------------------
932 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
933 bindIfaceId (occ, ty) thing_inside
934 = do { name <- newIfaceName (mkVarOccFS occ)
935 ; ty' <- tcIfaceType ty
936 ; let { id = mkLocalId name ty' }
937 ; extendIfaceIdEnv [id] (thing_inside id) }
939 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
940 bindIfaceIds bndrs thing_inside
941 = do { names <- newIfaceNames (map mkVarOccFS occs)
942 ; tys' <- mappM tcIfaceType tys
943 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
944 ; extendIfaceIdEnv ids (thing_inside ids) }
946 (occs,tys) = unzip bndrs
949 -----------------------
950 newExtCoreBndr :: IfaceIdBndr -> IfL Id
951 newExtCoreBndr (var, ty)
952 = do { mod <- getIfModule
953 ; name <- newGlobalBinder mod (mkVarOccFS var) Nothing noSrcLoc
954 ; ty' <- tcIfaceType ty
955 ; return (mkLocalId name ty') }
957 -----------------------
958 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
959 bindIfaceTyVar (occ,kind) thing_inside
960 = do { name <- newIfaceName (mkTyVarOcc occ)
961 ; tyvar <- mk_iface_tyvar name kind
962 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
964 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
965 bindIfaceTyVars bndrs thing_inside
966 = do { names <- newIfaceNames (map mkTyVarOcc occs)
967 ; tyvars <- zipWithM mk_iface_tyvar names kinds
968 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
970 (occs,kinds) = unzip bndrs
972 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
973 mk_iface_tyvar name ifKind = do { kind <- tcIfaceType ifKind
974 ; return (mkTyVar name kind)
977 mk_iface_tyvar name kind = mkTyVar name kind