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 TcType ( hoistForAllTys ) -- TEMPORARY HACK
26 import Type ( liftedTypeKind, splitTyConApp, mkSynTy, mkTyConApp,
27 mkTyVarTys, ThetaType,
28 mkGenTyConApp ) -- Don't remove this... see mkIfTcApp
29 import TypeRep ( Type(..), PredType(..) )
30 import TyCon ( TyCon, tyConName, isSynTyCon )
31 import HscTypes ( ExternalPackageState(..),
32 TyThing(..), tyThingClass, tyThingTyCon,
33 ModIface(..), ModDetails(..), HomeModInfo(..),
34 emptyModDetails, lookupTypeEnv, lookupType, typeEnvIds )
35 import InstEnv ( Instance(..), mkImportedInstance )
37 import CoreUtils ( exprType )
39 import CoreLint ( lintUnfolding )
40 import WorkWrap ( mkWrapper )
41 import Id ( Id, mkVanillaGlobal, mkLocalId )
42 import MkId ( mkFCallId )
43 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
44 setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
45 setArityInfo, setInlinePragInfo, setCafInfo,
46 vanillaIdInfo, newStrictnessInfo )
47 import Class ( Class )
48 import TyCon ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
49 import DataCon ( DataCon, dataConWorkId, dataConTyVars, dataConInstArgTys, isVanillaDataCon )
50 import TysWiredIn ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
51 import Var ( TyVar, mkTyVar, tyVarKind )
52 import Name ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
53 wiredInNameTyThing_maybe, nameParent )
55 import OccName ( OccName )
56 import Module ( Module, lookupModuleEnv )
57 import UniqSupply ( initUs_ )
59 import ErrUtils ( Message )
60 import Maybes ( MaybeErr(..) )
61 import SrcLoc ( noSrcLoc )
62 import Util ( zipWithEqual, dropList, equalLength )
63 import DynFlags ( DynFlag(..), isOneShot )
72 An IfaceDecl is populated with RdrNames, and these are not renamed to
73 Names before typechecking, because there should be no scope errors etc.
75 -- For (b) consider: f = $(...h....)
76 -- where h is imported, and calls f via an hi-boot file.
77 -- This is bad! But it is not seen as a staging error, because h
78 -- is indeed imported. We don't want the type-checker to black-hole
79 -- when simplifying and compiling the splice!
81 -- Simple solution: discard any unfolding that mentions a variable
82 -- bound in this module (and hence not yet processed).
83 -- The discarding happens when forkM finds a type error.
85 %************************************************************************
87 %* tcImportDecl is the key function for "faulting in" *
90 %************************************************************************
92 The main idea is this. We are chugging along type-checking source code, and
93 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
94 it in the EPS type envt. So it
96 2 gets the decl for GHC.Base.map
97 3 typechecks it via tcIfaceDecl
98 4 and adds it to the type env in the EPS
100 Note that DURING STEP 4, we may find that map's type mentions a type
101 constructor that also
103 Notice that for imported things we read the current version from the EPS
104 mutable variable. This is important in situations like
106 where the code that e1 expands to might import some defns that
107 also turn out to be needed by the code that e2 expands to.
110 tcImportDecl :: Name -> TcM TyThing
111 -- Entry point for *source-code* uses of importDecl
113 | Just thing <- wiredInNameTyThing_maybe name
114 = do { initIfaceTcRn (loadWiredInHomeIface name)
117 = do { traceIf (text "tcImportDecl" <+> ppr name)
118 ; mb_thing <- initIfaceTcRn (importDecl name)
120 Succeeded thing -> return thing
121 Failed err -> failWithTc err }
123 checkWiredInTyCon :: TyCon -> TcM ()
124 -- Ensure that the home module of the TyCon (and hence its instances)
125 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
126 -- in which case this is a no-op.
128 | not (isWiredInName tc_name)
131 = do { mod <- getModule
132 ; if nameIsLocalOrFrom mod tc_name then
133 -- Don't look for (non-existent) Float.hi when
134 -- compiling Float.lhs, which mentions Float of course
136 else -- A bit yukky to call initIfaceTcRn here
137 initIfaceTcRn (loadWiredInHomeIface tc_name)
140 tc_name = tyConName tc
142 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
143 -- Get the TyThing for this Name from an interface file
144 -- It's not a wired-in thing -- the caller caught that
146 = ASSERT( not (isWiredInName name) )
149 -- Load the interface, which should populate the PTE
150 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
152 Failed err_msg -> return (Failed err_msg) ;
153 Succeeded iface -> do
155 -- Now look it up again; this time we should find it
157 ; case lookupTypeEnv (eps_PTE eps) name of
158 Just thing -> return (Succeeded thing)
159 Nothing -> return (Failed not_found_msg)
162 nd_doc = ptext SLIT("Need decl for") <+> ppr name
163 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+> ppr (nameParent name))
164 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
165 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
168 %************************************************************************
170 Type-checking a complete interface
172 %************************************************************************
174 Suppose we discover we don't need to recompile. Then we must type
175 check the old interface file. This is a bit different to the
176 incremental type checking we do as we suck in interface files. Instead
177 we do things similarly as when we are typechecking source decls: we
178 bring into scope the type envt for the interface all at once, using a
179 knot. Remember, the decls aren't necessarily in dependency order --
180 and even if they were, the type decls might be mutually recursive.
183 typecheckIface :: ModIface -- Get the decls from here
184 -> TcRnIf gbl lcl ModDetails
186 = initIfaceTc iface $ \ tc_env_var -> do
187 -- The tc_env_var is freshly allocated, private to
188 -- type-checking this particular interface
189 { -- Get the right set of decls and rules. If we are compiling without -O
190 -- we discard pragmas before typechecking, so that we don't "see"
191 -- information that we shouldn't. From a versioning point of view
192 -- It's not actually *wrong* to do so, but in fact GHCi is unable
193 -- to handle unboxed tuples, so it must not see unfoldings.
194 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
196 -- Load & typecheck the decls
197 ; decl_things <- loadDecls ignore_prags (mi_decls iface)
199 ; let type_env = mkNameEnv decl_things
200 ; writeMutVar tc_env_var type_env
202 -- Now do those rules and instances
203 ; let { rules | ignore_prags = []
204 | otherwise = mi_rules iface
205 ; dfuns = mi_insts iface
207 ; dfuns <- mapM tcIfaceInst dfuns
208 ; rules <- mapM tcIfaceRule rules
211 ; exports <- ifaceExportNames (mi_exports iface)
214 ; return (ModDetails { md_types = type_env,
217 md_exports = exports })
222 %************************************************************************
224 Type and class declarations
226 %************************************************************************
229 tcHiBootIface :: Module -> TcRn ModDetails
230 -- Load the hi-boot iface for the module being compiled,
231 -- if it indeed exists in the transitive closure of imports
232 -- Return the ModDetails, empty if no hi-boot iface
234 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
236 ; mode <- getGhciMode
237 ; if not (isOneShot mode)
238 -- In --make and interactive mode, if this module has an hs-boot file
239 -- we'll have compiled it already, and it'll be in the HPT
241 -- We check wheher the interface is a *boot* interface.
242 -- It can happen (when using GHC from Visual Studio) that we
243 -- compile a module in TypecheckOnly mode, with a stable,
244 -- fully-populated HPT. In that case the boot interface isn't there
245 -- (it's been replaced by the mother module) so we can't check it.
246 -- And that's fine, because if M's ModInfo is in the HPT, then
247 -- it's been compiled once, and we don't need to check the boot iface
248 then do { hpt <- getHpt
249 ; case lookupModuleEnv hpt mod of
250 Just info | mi_boot (hm_iface info)
251 -> return (hm_details info)
252 other -> return emptyModDetails }
255 -- OK, so we're in one-shot mode.
256 -- In that case, we're read all the direct imports by now,
257 -- so eps_is_boot will record if any of our imports mention us by
258 -- way of hi-boot file
260 ; case lookupModuleEnv (eps_is_boot eps) mod of {
261 Nothing -> return emptyModDetails ; -- The typical case
263 Just (_, False) -> failWithTc moduleLoop ;
264 -- Someone below us imported us!
265 -- This is a loop with no hi-boot in the way
267 Just (mod, True) -> -- There's a hi-boot interface below us
269 do { read_result <- findAndReadIface
270 True -- Explicit import?
274 ; case read_result of
275 Failed err -> failWithTc (elaborate err)
276 Succeeded (iface, _path) -> typecheckIface iface
279 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
280 <+> ptext SLIT("to compare against the Real Thing")
282 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
283 <+> ptext SLIT("depends on itself")
285 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
286 quotes (ppr mod) <> colon) 4 err
290 %************************************************************************
292 Type and class declarations
294 %************************************************************************
296 When typechecking a data type decl, we *lazily* (via forkM) typecheck
297 the constructor argument types. This is in the hope that we may never
298 poke on those argument types, and hence may never need to load the
299 interface files for types mentioned in the arg types.
302 data Foo.S = MkS Baz.T
303 Mabye we can get away without even loading the interface for Baz!
305 This is not just a performance thing. Suppose we have
306 data Foo.S = MkS Baz.T
307 data Baz.T = MkT Foo.S
308 (in different interface files, of course).
309 Now, first we load and typecheck Foo.S, and add it to the type envt.
310 If we do explore MkS's argument, we'll load and typecheck Baz.T.
311 If we explore MkT's argument we'll find Foo.S already in the envt.
313 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
314 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
315 which isn't done yet.
317 All very cunning. However, there is a rather subtle gotcha which bit
318 me when developing this stuff. When we typecheck the decl for S, we
319 extend the type envt with S, MkS, and all its implicit Ids. Suppose
320 (a bug, but it happened) that the list of implicit Ids depended in
321 turn on the constructor arg types. Then the following sequence of
323 * we build a thunk <t> for the constructor arg tys
324 * we build a thunk for the extended type environment (depends on <t>)
325 * we write the extended type envt into the global EPS mutvar
327 Now we look something up in the type envt
329 * which reads the global type envt out of the global EPS mutvar
330 * but that depends in turn on <t>
332 It's subtle, because, it'd work fine if we typechecked the constructor args
333 eagerly -- they don't need the extended type envt. They just get the extended
334 type envt by accident, because they look at it later.
336 What this means is that the implicitTyThings MUST NOT DEPEND on any of
341 tcIfaceDecl :: IfaceDecl -> IfL TyThing
343 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
344 = do { name <- lookupIfaceTop occ_name
345 ; ty <- tcIfaceType iface_type
346 ; info <- tcIdInfo name ty info
347 ; return (AnId (mkVanillaGlobal name ty info)) }
349 tcIfaceDecl (IfaceData {ifName = occ_name,
353 ifVrcs = arg_vrcs, ifRec = is_rec,
354 ifGeneric = want_generic })
355 = do { tc_name <- lookupIfaceTop occ_name
356 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
358 { tycon <- fixM ( \ tycon -> do
359 { stupid_theta <- tcIfaceCtxt ctxt
360 ; cons <- tcIfaceDataCons tycon tyvars rdr_cons
361 ; buildAlgTyCon tc_name tyvars stupid_theta
362 cons arg_vrcs is_rec want_generic
364 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
365 ; return (ATyCon tycon)
368 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
369 ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
370 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
371 { tc_name <- lookupIfaceTop occ_name
372 ; rhs_ty <- tcIfaceType rdr_rhs_ty
373 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
376 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs,
377 ifFDs = rdr_fds, ifSigs = rdr_sigs,
378 ifVrcs = tc_vrcs, ifRec = tc_isrec })
379 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
380 { cls_name <- lookupIfaceTop occ_name
381 ; ctxt <- tcIfaceCtxt rdr_ctxt
382 ; sigs <- mappM tc_sig rdr_sigs
383 ; fds <- mappM tc_fd rdr_fds
384 ; cls <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
385 ; return (AClass cls) }
387 tc_sig (IfaceClassOp occ dm rdr_ty)
388 = do { op_name <- lookupIfaceTop occ
389 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
390 -- Must be done lazily for just the same reason as the
391 -- context of a data decl: the type sig might mention the
392 -- class being defined
393 ; return (op_name, dm, op_ty) }
395 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
397 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
398 ; tvs2' <- mappM tcIfaceTyVar tvs2
399 ; return (tvs1', tvs2') }
401 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
402 = do { name <- lookupIfaceTop rdr_name
403 ; return (ATyCon (mkForeignTyCon name ext_name
404 liftedTypeKind 0 [])) }
406 tcIfaceDataCons tycon tc_tyvars if_cons
408 IfAbstractTyCon -> return mkAbstractTyConRhs
409 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
410 ; return (mkDataTyConRhs data_cons) }
411 IfNewTyCon con -> do { data_con <- tc_con_decl con
412 ; return (mkNewTyConRhs tycon data_con) }
414 tc_con_decl (IfVanillaCon { ifConOcc = occ, ifConInfix = is_infix, ifConArgTys = args,
415 ifConStricts = stricts, ifConFields = field_lbls})
416 = do { name <- lookupIfaceTop occ
417 -- Read the argument types, but lazily to avoid faulting in
418 -- the component types unless they are really needed
419 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
420 ; lbl_names <- mappM lookupIfaceTop field_lbls
421 ; buildDataCon name is_infix True {- Vanilla -}
423 tc_tyvars [] arg_tys tycon
424 (mkTyVarTys tc_tyvars) -- Vanilla => we know result tys
427 tc_con_decl (IfGadtCon { ifConTyVars = con_tvs,
428 ifConOcc = occ, ifConCtxt = ctxt,
429 ifConArgTys = args, ifConResTys = ress,
430 ifConStricts = stricts})
431 = bindIfaceTyVars con_tvs $ \ con_tyvars -> do
432 { name <- lookupIfaceTop occ
433 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
434 -- At one stage I thought that this context checking *had*
435 -- to be lazy, because of possible mutual recursion between the
436 -- type and the classe:
438 -- class Real a where { toRat :: a -> Ratio Integer }
439 -- data (Real a) => Ratio a = ...
440 -- But now I think that the laziness in checking class ops breaks
441 -- the loop, so no laziness needed
443 -- Read the argument types, but lazily to avoid faulting in
444 -- the component types unless they are really needed
445 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
446 ; res_tys <- forkM (mk_doc name) (mappM tcIfaceType ress)
448 ; buildDataCon name False {- Not infix -} False {- Not vanilla -}
449 stricts [{- No fields -}]
451 arg_tys tycon res_tys
453 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
457 %************************************************************************
461 %************************************************************************
464 tcIfaceInst :: IfaceInst -> IfL Instance
465 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
466 ifInstCls = cls, ifInstTys = mb_tcs,
468 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
469 tcIfaceExtId (LocalTop dfun_occ)
470 ; cls' <- lookupIfaceExt cls
471 ; mb_tcs' <- mapM do_tc mb_tcs
472 ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
474 do_tc Nothing = return Nothing
475 do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
479 %************************************************************************
483 %************************************************************************
485 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
486 are in the type environment. However, remember that typechecking a Rule may
487 (as a side effect) augment the type envt, and so we may need to iterate the process.
490 tcIfaceRule :: IfaceRule -> IfL CoreRule
491 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
492 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
494 = do { fn' <- lookupIfaceExt fn
495 ; ~(bndrs', args', rhs') <-
496 -- Typecheck the payload lazily, in the hope it'll never be looked at
497 forkM (ptext SLIT("Rule") <+> ftext name) $
498 bindIfaceBndrs bndrs $ \ bndrs' ->
499 do { args' <- mappM tcIfaceExpr args
500 ; rhs' <- tcIfaceExpr rhs
501 ; return (bndrs', args', rhs') }
502 ; mb_tcs <- mapM ifTopFreeName args
503 ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act,
504 ru_bndrs = bndrs', ru_args = args',
505 ru_rhs = rhs', ru_orph = orph,
507 ru_local = isLocalIfaceExtName fn }) }
509 -- This function *must* mirror exactly what Rules.topFreeName does
510 -- We could have stored the ru_rough field in the iface file
511 -- but that would be redundant, I think.
512 -- The only wrinkle is that we must not be deceived by
513 -- type syononyms at the top of a type arg. Since
514 -- we can't tell at this point, we are careful not
515 -- to write them out in coreRuleToIfaceRule
516 ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
517 ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
518 = do { n <- lookupIfaceTc tc
520 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
521 ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
523 ifTopFreeName other = return Nothing
527 %************************************************************************
531 %************************************************************************
534 tcIfaceType :: IfaceType -> IfL Type
535 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
536 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
537 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
538 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkIfTcApp tc' ts') }
539 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
540 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
542 tcIfaceTypes tys = mapM tcIfaceType tys
544 mkIfTcApp :: TyCon -> [Type] -> Type
545 -- In interface files we retain type synonyms (for brevity and better error
546 -- messages), but type synonyms can expand into non-hoisted types (ones with
547 -- foralls to the right of an arrow), so we must be careful to hoist them here.
548 -- This hack should go away when we get rid of hoisting.
549 -- Then we should go back to mkGenTyConApp or something like it
551 | isSynTyCon tc = hoistForAllTys (mkSynTy tc tys)
552 | otherwise = mkTyConApp tc tys
554 -----------------------------------------
555 tcIfacePredType :: IfacePredType -> IfL PredType
556 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
557 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
559 -----------------------------------------
560 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
561 tcIfaceCtxt sts = mappM tcIfacePredType sts
565 %************************************************************************
569 %************************************************************************
572 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
573 tcIfaceExpr (IfaceType ty)
574 = tcIfaceType ty `thenM` \ ty' ->
577 tcIfaceExpr (IfaceLcl name)
578 = tcIfaceLclId name `thenM` \ id ->
581 tcIfaceExpr (IfaceExt gbl)
582 = tcIfaceExtId gbl `thenM` \ id ->
585 tcIfaceExpr (IfaceLit lit)
588 tcIfaceExpr (IfaceFCall cc ty)
589 = tcIfaceType ty `thenM` \ ty' ->
590 newUnique `thenM` \ u ->
591 returnM (Var (mkFCallId u cc ty'))
593 tcIfaceExpr (IfaceTuple boxity args)
594 = mappM tcIfaceExpr args `thenM` \ args' ->
596 -- Put the missing type arguments back in
597 con_args = map (Type . exprType) args' ++ args'
599 returnM (mkApps (Var con_id) con_args)
602 con_id = dataConWorkId (tupleCon boxity arity)
605 tcIfaceExpr (IfaceLam bndr body)
606 = bindIfaceBndr bndr $ \ bndr' ->
607 tcIfaceExpr body `thenM` \ body' ->
608 returnM (Lam bndr' body')
610 tcIfaceExpr (IfaceApp fun arg)
611 = tcIfaceExpr fun `thenM` \ fun' ->
612 tcIfaceExpr arg `thenM` \ arg' ->
613 returnM (App fun' arg')
615 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
616 = tcIfaceExpr scrut `thenM` \ scrut' ->
617 newIfaceName case_bndr `thenM` \ case_bndr_name ->
619 scrut_ty = exprType scrut'
620 case_bndr' = mkLocalId case_bndr_name scrut_ty
621 tc_app = splitTyConApp scrut_ty
622 -- NB: Won't always succeed (polymoprhic case)
623 -- but won't be demanded in those cases
624 -- NB: not tcSplitTyConApp; we are looking at Core here
625 -- look through non-rec newtypes to find the tycon that
626 -- corresponds to the datacon in this case alternative
628 extendIfaceIdEnv [case_bndr'] $
629 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
630 tcIfaceType ty `thenM` \ ty' ->
631 returnM (Case scrut' case_bndr' ty' alts')
633 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
634 = tcIfaceExpr rhs `thenM` \ rhs' ->
635 bindIfaceId bndr $ \ bndr' ->
636 tcIfaceExpr body `thenM` \ body' ->
637 returnM (Let (NonRec bndr' rhs') body')
639 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
640 = bindIfaceIds bndrs $ \ bndrs' ->
641 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
642 tcIfaceExpr body `thenM` \ body' ->
643 returnM (Let (Rec (bndrs' `zip` rhss')) body')
645 (bndrs, rhss) = unzip pairs
647 tcIfaceExpr (IfaceNote note expr)
648 = tcIfaceExpr expr `thenM` \ expr' ->
650 IfaceCoerce to_ty -> tcIfaceType to_ty `thenM` \ to_ty' ->
651 returnM (Note (Coerce to_ty'
652 (exprType expr')) expr')
653 IfaceInlineCall -> returnM (Note InlineCall expr')
654 IfaceInlineMe -> returnM (Note InlineMe expr')
655 IfaceSCC cc -> returnM (Note (SCC cc) expr')
656 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
658 -------------------------
659 tcIfaceAlt _ (IfaceDefault, names, rhs)
660 = ASSERT( null names )
661 tcIfaceExpr rhs `thenM` \ rhs' ->
662 returnM (DEFAULT, [], rhs')
664 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
665 = ASSERT( null names )
666 tcIfaceExpr rhs `thenM` \ rhs' ->
667 returnM (LitAlt lit, [], rhs')
669 -- A case alternative is made quite a bit more complicated
670 -- by the fact that we omit type annotations because we can
671 -- work them out. True enough, but its not that easy!
672 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
673 = do { let tycon_mod = nameModule (tyConName tycon)
674 ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
675 ; ASSERT2( con `elem` tyConDataCons tycon,
676 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
678 if isVanillaDataCon con then
679 tcVanillaAlt con inst_tys arg_occs rhs
682 arg_names <- newIfaceNames arg_occs
683 ; let tyvars = [ mkTyVar name (tyVarKind tv)
684 | (name,tv) <- arg_names `zip` dataConTyVars con]
685 arg_tys = dataConInstArgTys con (mkTyVarTys tyvars)
686 id_names = dropList tyvars arg_names
687 arg_ids = ASSERT2( equalLength id_names arg_tys,
688 ppr (con, arg_names, rhs) $$ ppr tyvars $$ ppr arg_tys )
689 zipWith mkLocalId id_names arg_tys
691 ; rhs' <- extendIfaceTyVarEnv tyvars $
692 extendIfaceIdEnv arg_ids $
694 ; return (DataAlt con, tyvars ++ arg_ids, rhs') }}
696 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
697 = ASSERT( isTupleTyCon tycon )
698 do { let [data_con] = tyConDataCons tycon
699 ; tcVanillaAlt data_con inst_tys arg_occs rhs }
701 tcVanillaAlt data_con inst_tys arg_occs rhs
702 = do { arg_names <- newIfaceNames arg_occs
703 ; let arg_tys = dataConInstArgTys data_con inst_tys
704 ; let arg_ids = ASSERT2( equalLength arg_names arg_tys,
705 ppr data_con <+> ppr inst_tys <+> ppr arg_occs $$ ppr rhs )
706 zipWith mkLocalId arg_names arg_tys
707 ; rhs' <- extendIfaceIdEnv arg_ids (tcIfaceExpr rhs)
708 ; returnM (DataAlt data_con, arg_ids, rhs') }
713 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
714 tcExtCoreBindings [] = return []
715 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
717 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
718 do_one (IfaceNonRec bndr rhs) thing_inside
719 = do { rhs' <- tcIfaceExpr rhs
720 ; bndr' <- newExtCoreBndr bndr
721 ; extendIfaceIdEnv [bndr'] $ do
722 { core_binds <- thing_inside
723 ; return (NonRec bndr' rhs' : core_binds) }}
725 do_one (IfaceRec pairs) thing_inside
726 = do { bndrs' <- mappM newExtCoreBndr bndrs
727 ; extendIfaceIdEnv bndrs' $ do
728 { rhss' <- mappM tcIfaceExpr rhss
729 ; core_binds <- thing_inside
730 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
732 (bndrs,rhss) = unzip pairs
736 %************************************************************************
740 %************************************************************************
743 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
744 tcIdInfo name ty NoInfo = return vanillaIdInfo
745 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
747 -- Set the CgInfo to something sensible but uninformative before
748 -- we start; default assumption is that it has CAFs
749 init_info = vanillaIdInfo
751 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
752 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
753 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
755 -- The next two are lazy, so they don't transitively suck stuff in
756 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
757 tcPrag info (HsUnfold inline_prag expr)
758 = tcPragExpr name expr `thenM` \ maybe_expr' ->
760 -- maybe_expr' doesn't get looked at if the unfolding
761 -- is never inspected; so the typecheck doesn't even happen
762 unfold_info = case maybe_expr' of
763 Nothing -> noUnfolding
764 Just expr' -> mkTopUnfolding expr'
766 returnM (info `setUnfoldingInfoLazily` unfold_info
767 `setInlinePragInfo` inline_prag)
771 tcWorkerInfo ty info wkr arity
772 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
774 -- We return without testing maybe_wkr_id, but as soon as info is
775 -- looked at we will test it. That's ok, because its outside the
776 -- knot; and there seems no big reason to further defer the
777 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
778 -- over the unfolding until it's actually used does seem worth while.)
779 ; us <- newUniqueSupply
781 ; returnM (case mb_wkr_id of
783 Just wkr_id -> add_wkr_info us wkr_id info) }
785 doc = text "Worker for" <+> ppr wkr
786 add_wkr_info us wkr_id info
787 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
788 `setWorkerInfo` HasWorker wkr_id arity
790 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
792 -- We are relying here on strictness info always appearing
793 -- before worker info, fingers crossed ....
794 strict_sig = case newStrictnessInfo info of
796 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
799 For unfoldings we try to do the job lazily, so that we never type check
800 an unfolding that isn't going to be looked at.
803 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
806 tcIfaceExpr expr `thenM` \ core_expr' ->
808 -- Check for type consistency in the unfolding
809 ifOptM Opt_DoCoreLinting (
810 get_in_scope_ids `thenM` \ in_scope ->
811 case lintUnfolding noSrcLoc in_scope core_expr' of
812 Nothing -> returnM ()
813 Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
818 doc = text "Unfolding of" <+> ppr name
819 get_in_scope_ids -- Urgh; but just for linting
821 do { env <- getGblEnv
822 ; case if_rec_types env of {
823 Nothing -> return [] ;
824 Just (_, get_env) -> do
825 { type_env <- get_env
826 ; return (typeEnvIds type_env) }}}
831 %************************************************************************
833 Getting from Names to TyThings
835 %************************************************************************
838 tcIfaceGlobal :: Name -> IfL TyThing
840 | Just thing <- wiredInNameTyThing_maybe name
841 -- Wired-in things include TyCons, DataCons, and Ids
842 = do { loadWiredInHomeIface name; return thing }
843 -- Even though we are in an interface file, we want to make
844 -- sure its instances are loaded (imagine f :: Double -> Double)
845 -- and its RULES are loaded too
847 = do { (eps,hpt) <- getEpsAndHpt
848 ; case lookupType hpt (eps_PTE eps) name of {
849 Just thing -> return thing ;
853 ; case if_rec_types env of {
854 Just (mod, get_type_env)
855 | nameIsLocalOrFrom mod name
856 -> do -- It's defined in the module being compiled
857 { type_env <- setLclEnv () get_type_env -- yuk
858 ; case lookupNameEnv type_env name of
859 Just thing -> return thing
860 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
861 (ppr name $$ ppr type_env) }
865 { mb_thing <- importDecl name -- It's imported; go get it
867 Failed err -> failIfM err
868 Succeeded thing -> return thing
871 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
872 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
873 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
874 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
875 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
876 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
877 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
878 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
879 ; thing <- tcIfaceGlobal name
880 ; return (check_tc (tyThingTyCon thing)) }
883 check_tc tc = case toIfaceTyCon (error "urk") tc of
885 other -> pprTrace "check_tc" (ppr tc) tc
890 -- Even though we are in an interface file, we want to make
891 -- sure the instances and RULES of this tycon are loaded
892 -- Imagine: f :: Double -> Double
893 tcWiredInTyCon :: TyCon -> IfL TyCon
894 tcWiredInTyCon tc = do { loadWiredInHomeIface (tyConName tc)
897 tcIfaceClass :: IfaceExtName -> IfL Class
898 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
899 ; thing <- tcIfaceGlobal name
900 ; return (tyThingClass thing) }
902 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
903 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
904 ; thing <- tcIfaceGlobal name
906 ADataCon dc -> return dc
907 other -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
909 tcIfaceExtId :: IfaceExtName -> IfL Id
910 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
911 ; thing <- tcIfaceGlobal name
914 other -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
917 %************************************************************************
921 %************************************************************************
924 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
925 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
926 = bindIfaceId bndr thing_inside
927 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
928 = bindIfaceTyVar bndr thing_inside
930 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
931 bindIfaceBndrs [] thing_inside = thing_inside []
932 bindIfaceBndrs (b:bs) thing_inside
933 = bindIfaceBndr b $ \ b' ->
934 bindIfaceBndrs bs $ \ bs' ->
935 thing_inside (b':bs')
937 -----------------------
938 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
939 bindIfaceId (occ, ty) thing_inside
940 = do { name <- newIfaceName occ
941 ; ty' <- tcIfaceType ty
942 ; let { id = mkLocalId name ty' }
943 ; extendIfaceIdEnv [id] (thing_inside id) }
945 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
946 bindIfaceIds bndrs thing_inside
947 = do { names <- newIfaceNames occs
948 ; tys' <- mappM tcIfaceType tys
949 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
950 ; extendIfaceIdEnv ids (thing_inside ids) }
952 (occs,tys) = unzip bndrs
955 -----------------------
956 newExtCoreBndr :: (OccName, IfaceType) -> IfL Id
957 newExtCoreBndr (occ, ty)
958 = do { mod <- getIfModule
959 ; name <- newGlobalBinder mod occ Nothing noSrcLoc
960 ; ty' <- tcIfaceType ty
961 ; return (mkLocalId name ty') }
963 -----------------------
964 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
965 bindIfaceTyVar (occ,kind) thing_inside
966 = do { name <- newIfaceName occ
967 ; let tyvar = mk_iface_tyvar name kind
968 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
970 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
971 bindIfaceTyVars bndrs thing_inside
972 = do { names <- newIfaceNames occs
973 ; let tyvars = zipWith mk_iface_tyvar names kinds
974 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
976 (occs,kinds) = unzip bndrs
978 mk_iface_tyvar name kind = mkTyVar name kind