2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Type checking of type signatures in interface files
10 tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
11 tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
12 tcIfaceVectInfo, tcIfaceGlobal, tcExtCoreBindings
15 #include "HsVersions.h"
65 An IfaceDecl is populated with RdrNames, and these are not renamed to
66 Names before typechecking, because there should be no scope errors etc.
68 -- For (b) consider: f = $(...h....)
69 -- where h is imported, and calls f via an hi-boot file.
70 -- This is bad! But it is not seen as a staging error, because h
71 -- is indeed imported. We don't want the type-checker to black-hole
72 -- when simplifying and compiling the splice!
74 -- Simple solution: discard any unfolding that mentions a variable
75 -- bound in this module (and hence not yet processed).
76 -- The discarding happens when forkM finds a type error.
78 %************************************************************************
80 %* tcImportDecl is the key function for "faulting in" *
83 %************************************************************************
85 The main idea is this. We are chugging along type-checking source code, and
86 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
87 it in the EPS type envt. So it
89 2 gets the decl for GHC.Base.map
90 3 typechecks it via tcIfaceDecl
91 4 and adds it to the type env in the EPS
93 Note that DURING STEP 4, we may find that map's type mentions a type
96 Notice that for imported things we read the current version from the EPS
97 mutable variable. This is important in situations like
99 where the code that e1 expands to might import some defns that
100 also turn out to be needed by the code that e2 expands to.
103 tcImportDecl :: Name -> TcM TyThing
104 -- Entry point for *source-code* uses of importDecl
106 | Just thing <- wiredInNameTyThing_maybe name
107 = do { initIfaceTcRn (loadWiredInHomeIface name)
110 = do { traceIf (text "tcImportDecl" <+> ppr name)
111 ; mb_thing <- initIfaceTcRn (importDecl name)
113 Succeeded thing -> return thing
114 Failed err -> failWithTc err }
116 checkWiredInTyCon :: TyCon -> TcM ()
117 -- Ensure that the home module of the TyCon (and hence its instances)
118 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
119 -- in which case this is a no-op.
121 | not (isWiredInName tc_name)
124 = do { mod <- getModule
125 ; unless (mod == nameModule tc_name)
126 (initIfaceTcRn (loadWiredInHomeIface tc_name))
127 -- Don't look for (non-existent) Float.hi when
128 -- compiling Float.lhs, which mentions Float of course
129 -- A bit yukky to call initIfaceTcRn here
132 tc_name = tyConName tc
134 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
135 -- Get the TyThing for this Name from an interface file
136 -- It's not a wired-in thing -- the caller caught that
138 = ASSERT( not (isWiredInName name) )
141 -- Load the interface, which should populate the PTE
142 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
144 Failed err_msg -> return (Failed err_msg) ;
145 Succeeded iface -> do
147 -- Now look it up again; this time we should find it
149 ; case lookupTypeEnv (eps_PTE eps) name of
150 Just thing -> return (Succeeded thing)
151 Nothing -> return (Failed not_found_msg)
154 nd_doc = ptext SLIT("Need decl for") <+> ppr name
155 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
156 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
157 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
158 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
161 %************************************************************************
163 Type-checking a complete interface
165 %************************************************************************
167 Suppose we discover we don't need to recompile. Then we must type
168 check the old interface file. This is a bit different to the
169 incremental type checking we do as we suck in interface files. Instead
170 we do things similarly as when we are typechecking source decls: we
171 bring into scope the type envt for the interface all at once, using a
172 knot. Remember, the decls aren't necessarily in dependency order --
173 and even if they were, the type decls might be mutually recursive.
176 typecheckIface :: ModIface -- Get the decls from here
177 -> TcRnIf gbl lcl ModDetails
179 = initIfaceTc iface $ \ tc_env_var -> do
180 -- The tc_env_var is freshly allocated, private to
181 -- type-checking this particular interface
182 { -- Get the right set of decls and rules. If we are compiling without -O
183 -- we discard pragmas before typechecking, so that we don't "see"
184 -- information that we shouldn't. From a versioning point of view
185 -- It's not actually *wrong* to do so, but in fact GHCi is unable
186 -- to handle unboxed tuples, so it must not see unfoldings.
187 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
189 -- Typecheck the decls. This is done lazily, so that the knot-tying
190 -- within this single module work out right. In the If monad there is
191 -- no global envt for the current interface; instead, the knot is tied
192 -- through the if_rec_types field of IfGblEnv
193 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
194 ; let type_env = mkNameEnv names_w_things
195 ; writeMutVar tc_env_var type_env
197 -- Now do those rules and instances
198 ; insts <- mapM tcIfaceInst (mi_insts iface)
199 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
200 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
202 -- Vectorisation information
203 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
207 ; exports <- ifaceExportNames (mi_exports iface)
210 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
211 text "Type envt:" <+> ppr type_env])
212 ; return $ ModDetails { md_types = type_env
214 , md_fam_insts = fam_insts
216 , md_vect_info = vect_info
217 , md_exports = exports
218 , md_modBreaks = emptyModBreaks
224 %************************************************************************
226 Type and class declarations
228 %************************************************************************
231 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
232 -- Load the hi-boot iface for the module being compiled,
233 -- if it indeed exists in the transitive closure of imports
234 -- Return the ModDetails, empty if no hi-boot iface
235 tcHiBootIface hsc_src mod
236 | isHsBoot hsc_src -- Already compiling a hs-boot file
237 = return emptyModDetails
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 :: Bool -- True <=> discard IdInfo on IfaceId bindings
349 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
350 = do { name <- lookupIfaceTop occ_name
351 ; ty <- tcIfaceType iface_type
352 ; info <- tcIdInfo ignore_prags name ty info
353 ; return (AnId (mkVanillaGlobal name ty info)) }
355 tcIfaceDecl ignore_prags
356 (IfaceData {ifName = occ_name,
358 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
361 ifGeneric = want_generic,
362 ifFamInst = mb_family })
363 = do { tc_name <- lookupIfaceTop occ_name
364 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
366 { tycon <- fixM ( \ tycon -> do
367 { stupid_theta <- tcIfaceCtxt ctxt
370 Nothing -> return Nothing
372 do { famTyCon <- tcIfaceTyCon fam
373 ; insttys <- mapM tcIfaceType tys
374 ; return $ Just (famTyCon, insttys)
376 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
377 ; buildAlgTyCon tc_name tyvars stupid_theta
378 cons is_rec want_generic gadt_syn famInst
380 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
381 ; return (ATyCon tycon)
384 tcIfaceDecl ignore_prags
385 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
386 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
387 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
388 { tc_name <- lookupIfaceTop occ_name
389 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
390 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
391 else SynonymTyCon rhs_tyki
392 -- !!!TODO: read mb_family info from iface and pass as last argument
393 ; tycon <- buildSynTyCon tc_name tyvars rhs Nothing
394 ; return $ ATyCon tycon
397 tcIfaceDecl ignore_prags
398 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
399 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
400 ifATs = rdr_ats, ifSigs = rdr_sigs,
402 -- ToDo: in hs-boot files we should really treat abstract classes specially,
403 -- as we do abstract tycons
404 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
405 { cls_name <- lookupIfaceTop occ_name
406 ; ctxt <- tcIfaceCtxt rdr_ctxt
407 ; sigs <- mappM tc_sig rdr_sigs
408 ; fds <- mappM tc_fd rdr_fds
409 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
410 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
411 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
412 ; return (AClass cls) }
414 tc_sig (IfaceClassOp occ dm rdr_ty)
415 = do { op_name <- lookupIfaceTop occ
416 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
417 -- Must be done lazily for just the same reason as the
418 -- type of a data con; to avoid sucking in types that
419 -- it mentions unless it's necessray to do so
420 ; return (op_name, dm, op_ty) }
422 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
424 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
425 ; tvs2' <- mappM tcIfaceTyVar tvs2
426 ; return (tvs1', tvs2') }
428 -- For each AT argument compute the position of the corresponding class
429 -- parameter in the class head. This will later serve as a permutation
430 -- vector when checking the validity of instance declarations.
431 setTyThingPoss (ATyCon tycon) atTyVars =
432 let classTyVars = map fst tv_bndrs
434 . map ((`elemIndex` classTyVars) . fst)
436 -- There will be no Nothing, as we already passed renaming
438 ATyCon (setTyConArgPoss tycon poss)
439 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
441 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
442 = do { name <- lookupIfaceTop rdr_name
443 ; return (ATyCon (mkForeignTyCon name ext_name
446 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
448 IfAbstractTyCon -> return mkAbstractTyConRhs
449 IfOpenDataTyCon -> return mkOpenDataTyConRhs
450 IfOpenNewTyCon -> return mkOpenNewTyConRhs
451 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
452 ; return (mkDataTyConRhs data_cons) }
453 IfNewTyCon con -> do { data_con <- tc_con_decl con
454 ; mkNewTyConRhs tycon_name tycon data_con }
456 tc_con_decl (IfCon { ifConInfix = is_infix,
457 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
458 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
459 ifConArgTys = args, ifConFields = field_lbls,
460 ifConStricts = stricts})
461 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
462 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
463 { name <- lookupIfaceTop occ
464 ; eq_spec <- tcIfaceEqSpec spec
465 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
466 -- At one stage I thought that this context checking *had*
467 -- to be lazy, because of possible mutual recursion between the
468 -- type and the classe:
470 -- class Real a where { toRat :: a -> Ratio Integer }
471 -- data (Real a) => Ratio a = ...
472 -- But now I think that the laziness in checking class ops breaks
473 -- the loop, so no laziness needed
475 -- Read the argument types, but lazily to avoid faulting in
476 -- the component types unless they are really needed
477 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
478 ; lbl_names <- mappM lookupIfaceTop field_lbls
480 ; buildDataCon name is_infix {- Not infix -}
482 univ_tyvars ex_tyvars
486 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
491 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
492 ; ty <- tcIfaceType if_ty
497 %************************************************************************
501 %************************************************************************
504 tcIfaceInst :: IfaceInst -> IfL Instance
505 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
506 ifInstCls = cls, ifInstTys = mb_tcs,
508 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
509 tcIfaceExtId dfun_occ
510 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
511 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
513 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
514 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
515 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
516 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
517 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
518 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
520 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
521 ; return (mkImportedFamInst fam mb_tcs' tycon') }
525 %************************************************************************
529 %************************************************************************
531 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
532 are in the type environment. However, remember that typechecking a Rule may
533 (as a side effect) augment the type envt, and so we may need to iterate the process.
536 tcIfaceRules :: Bool -- True <=> ignore rules
539 tcIfaceRules ignore_prags if_rules
540 | ignore_prags = return []
541 | otherwise = mapM tcIfaceRule if_rules
543 tcIfaceRule :: IfaceRule -> IfL CoreRule
544 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
545 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
547 = do { ~(bndrs', args', rhs') <-
548 -- Typecheck the payload lazily, in the hope it'll never be looked at
549 forkM (ptext SLIT("Rule") <+> ftext name) $
550 bindIfaceBndrs bndrs $ \ bndrs' ->
551 do { args' <- mappM tcIfaceExpr args
552 ; rhs' <- tcIfaceExpr rhs
553 ; return (bndrs', args', rhs') }
554 ; let mb_tcs = map ifTopFreeName args
556 ; returnM (Rule { ru_name = name, ru_fn = fn, ru_act = act,
557 ru_bndrs = bndrs', ru_args = args',
560 ru_local = False }) } -- An imported RULE is never for a local Id
561 -- or, even if it is (module loop, perhaps)
562 -- we'll just leave it in the non-local set
564 -- This function *must* mirror exactly what Rules.topFreeName does
565 -- We could have stored the ru_rough field in the iface file
566 -- but that would be redundant, I think.
567 -- The only wrinkle is that we must not be deceived by
568 -- type syononyms at the top of a type arg. Since
569 -- we can't tell at this point, we are careful not
570 -- to write them out in coreRuleToIfaceRule
571 ifTopFreeName :: IfaceExpr -> Maybe Name
572 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
573 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
574 ifTopFreeName (IfaceExt n) = Just n
575 ifTopFreeName other = Nothing
579 %************************************************************************
581 Vectorisation information
583 %************************************************************************
586 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
587 tcIfaceVectInfo mod typeEnv (IfaceVectInfo names)
588 = do { ccVars <- mapM ccMapping names
589 ; return $ VectInfo (mkVarEnv ccVars)
593 = do { ccName <- lookupOrig mod (mkCloOcc (nameOccName name))
594 ; let { var = lookup name
595 ; ccVar = lookup ccName
597 ; return (var, (var, ccVar))
599 lookup name = case lookupTypeEnv typeEnv name of
600 Just (AnId var) -> var
602 panic "TcIface.tcIfaceVectInfo: wrong TyThing"
604 panic "TcIface.tcIfaceVectInfo: unknown name"
607 %************************************************************************
611 %************************************************************************
614 tcIfaceType :: IfaceType -> IfL Type
615 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
616 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
617 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
618 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
619 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
620 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
622 tcIfaceTypes tys = mapM tcIfaceType tys
624 -----------------------------------------
625 tcIfacePredType :: IfacePredType -> IfL PredType
626 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
627 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
628 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
630 -----------------------------------------
631 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
632 tcIfaceCtxt sts = mappM tcIfacePredType sts
636 %************************************************************************
640 %************************************************************************
643 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
644 tcIfaceExpr (IfaceType ty)
645 = tcIfaceType ty `thenM` \ ty' ->
648 tcIfaceExpr (IfaceLcl name)
649 = tcIfaceLclId name `thenM` \ id ->
652 tcIfaceExpr (IfaceExt gbl)
653 = tcIfaceExtId gbl `thenM` \ id ->
656 tcIfaceExpr (IfaceLit lit)
659 tcIfaceExpr (IfaceFCall cc ty)
660 = tcIfaceType ty `thenM` \ ty' ->
661 newUnique `thenM` \ u ->
662 returnM (Var (mkFCallId u cc ty'))
664 tcIfaceExpr (IfaceTuple boxity args)
665 = mappM tcIfaceExpr args `thenM` \ args' ->
667 -- Put the missing type arguments back in
668 con_args = map (Type . exprType) args' ++ args'
670 returnM (mkApps (Var con_id) con_args)
673 con_id = dataConWorkId (tupleCon boxity arity)
676 tcIfaceExpr (IfaceLam bndr body)
677 = bindIfaceBndr bndr $ \ bndr' ->
678 tcIfaceExpr body `thenM` \ body' ->
679 returnM (Lam bndr' body')
681 tcIfaceExpr (IfaceApp fun arg)
682 = tcIfaceExpr fun `thenM` \ fun' ->
683 tcIfaceExpr arg `thenM` \ arg' ->
684 returnM (App fun' arg')
686 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
687 = tcIfaceExpr scrut `thenM` \ scrut' ->
688 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
690 scrut_ty = exprType scrut'
691 case_bndr' = mkLocalId case_bndr_name scrut_ty
692 tc_app = splitTyConApp scrut_ty
693 -- NB: Won't always succeed (polymoprhic case)
694 -- but won't be demanded in those cases
695 -- NB: not tcSplitTyConApp; we are looking at Core here
696 -- look through non-rec newtypes to find the tycon that
697 -- corresponds to the datacon in this case alternative
699 extendIfaceIdEnv [case_bndr'] $
700 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
701 tcIfaceType ty `thenM` \ ty' ->
702 returnM (Case scrut' case_bndr' ty' alts')
704 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
705 = do { rhs' <- tcIfaceExpr rhs
706 ; id <- tcIfaceLetBndr bndr
707 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
708 ; return (Let (NonRec id rhs') body') }
710 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
711 = do { ids <- mapM tcIfaceLetBndr bndrs
712 ; extendIfaceIdEnv ids $ do
713 { rhss' <- mapM tcIfaceExpr rhss
714 ; body' <- tcIfaceExpr body
715 ; return (Let (Rec (ids `zip` rhss')) body') } }
717 (bndrs, rhss) = unzip pairs
719 tcIfaceExpr (IfaceCast expr co) = do
720 expr' <- tcIfaceExpr expr
721 co' <- tcIfaceType co
722 returnM (Cast expr' co')
724 tcIfaceExpr (IfaceNote note expr)
725 = tcIfaceExpr expr `thenM` \ expr' ->
727 IfaceInlineMe -> returnM (Note InlineMe expr')
728 IfaceSCC cc -> returnM (Note (SCC cc) expr')
729 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
731 -------------------------
732 tcIfaceAlt _ (IfaceDefault, names, rhs)
733 = ASSERT( null names )
734 tcIfaceExpr rhs `thenM` \ rhs' ->
735 returnM (DEFAULT, [], rhs')
737 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
738 = ASSERT( null names )
739 tcIfaceExpr rhs `thenM` \ rhs' ->
740 returnM (LitAlt lit, [], rhs')
742 -- A case alternative is made quite a bit more complicated
743 -- by the fact that we omit type annotations because we can
744 -- work them out. True enough, but its not that easy!
745 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
746 = do { con <- tcIfaceDataCon data_occ
747 ; ASSERT2( con `elem` tyConDataCons tycon,
748 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
749 tcIfaceDataAlt con inst_tys arg_strs rhs }
751 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
752 = ASSERT( isTupleTyCon tycon )
753 do { let [data_con] = tyConDataCons tycon
754 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
756 tcIfaceDataAlt con inst_tys arg_strs rhs
757 = do { us <- newUniqueSupply
758 ; let uniqs = uniqsFromSupply us
759 ; let (ex_tvs, co_tvs, arg_ids)
760 = dataConRepFSInstPat arg_strs uniqs con inst_tys
761 all_tvs = ex_tvs ++ co_tvs
763 ; rhs' <- extendIfaceTyVarEnv all_tvs $
764 extendIfaceIdEnv arg_ids $
766 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
771 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
772 tcExtCoreBindings [] = return []
773 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
775 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
776 do_one (IfaceNonRec bndr rhs) thing_inside
777 = do { rhs' <- tcIfaceExpr rhs
778 ; bndr' <- newExtCoreBndr bndr
779 ; extendIfaceIdEnv [bndr'] $ do
780 { core_binds <- thing_inside
781 ; return (NonRec bndr' rhs' : core_binds) }}
783 do_one (IfaceRec pairs) thing_inside
784 = do { bndrs' <- mappM newExtCoreBndr bndrs
785 ; extendIfaceIdEnv bndrs' $ do
786 { rhss' <- mappM tcIfaceExpr rhss
787 ; core_binds <- thing_inside
788 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
790 (bndrs,rhss) = unzip pairs
794 %************************************************************************
798 %************************************************************************
801 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
802 tcIdInfo ignore_prags name ty info
803 | ignore_prags = return vanillaIdInfo
804 | otherwise = case info of
805 NoInfo -> return vanillaIdInfo
806 HasInfo info -> foldlM tcPrag init_info info
808 -- Set the CgInfo to something sensible but uninformative before
809 -- we start; default assumption is that it has CAFs
810 init_info = vanillaIdInfo
812 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
813 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
814 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
816 -- The next two are lazy, so they don't transitively suck stuff in
817 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
818 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
819 tcPrag info (HsUnfold expr)
820 = tcPragExpr name expr `thenM` \ maybe_expr' ->
822 -- maybe_expr' doesn't get looked at if the unfolding
823 -- is never inspected; so the typecheck doesn't even happen
824 unfold_info = case maybe_expr' of
825 Nothing -> noUnfolding
826 Just expr' -> mkTopUnfolding expr'
828 returnM (info `setUnfoldingInfoLazily` unfold_info)
832 tcWorkerInfo ty info wkr arity
833 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
835 -- We return without testing maybe_wkr_id, but as soon as info is
836 -- looked at we will test it. That's ok, because its outside the
837 -- knot; and there seems no big reason to further defer the
838 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
839 -- over the unfolding until it's actually used does seem worth while.)
840 ; us <- newUniqueSupply
842 ; returnM (case mb_wkr_id of
844 Just wkr_id -> add_wkr_info us wkr_id info) }
846 doc = text "Worker for" <+> ppr wkr
847 add_wkr_info us wkr_id info
848 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
849 `setWorkerInfo` HasWorker wkr_id arity
851 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
853 -- We are relying here on strictness info always appearing
854 -- before worker info, fingers crossed ....
855 strict_sig = case newStrictnessInfo info of
857 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
860 For unfoldings we try to do the job lazily, so that we never type check
861 an unfolding that isn't going to be looked at.
864 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
867 tcIfaceExpr expr `thenM` \ core_expr' ->
869 -- Check for type consistency in the unfolding
870 ifOptM Opt_DoCoreLinting (
871 get_in_scope_ids `thenM` \ in_scope ->
872 case lintUnfolding noSrcLoc in_scope core_expr' of
873 Nothing -> returnM ()
874 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
879 doc = text "Unfolding of" <+> ppr name
880 get_in_scope_ids -- Urgh; but just for linting
882 do { env <- getGblEnv
883 ; case if_rec_types env of {
884 Nothing -> return [] ;
885 Just (_, get_env) -> do
886 { type_env <- get_env
887 ; return (typeEnvIds type_env) }}}
892 %************************************************************************
894 Getting from Names to TyThings
896 %************************************************************************
899 tcIfaceGlobal :: Name -> IfL TyThing
901 | Just thing <- wiredInNameTyThing_maybe name
902 -- Wired-in things include TyCons, DataCons, and Ids
903 = do { ifCheckWiredInThing name; return thing }
905 = do { (eps,hpt) <- getEpsAndHpt
907 ; case lookupType dflags hpt (eps_PTE eps) name of {
908 Just thing -> return thing ;
912 ; case if_rec_types env of {
913 Just (mod, get_type_env)
914 | nameIsLocalOrFrom mod name
915 -> do -- It's defined in the module being compiled
916 { type_env <- setLclEnv () get_type_env -- yuk
917 ; case lookupNameEnv type_env name of
918 Just thing -> return thing
919 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
920 (ppr name $$ ppr type_env) }
924 { mb_thing <- importDecl name -- It's imported; go get it
926 Failed err -> failIfM err
927 Succeeded thing -> return thing
930 ifCheckWiredInThing :: Name -> IfL ()
931 -- Even though we are in an interface file, we want to make
932 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
933 -- Ditto want to ensure that RULES are loaded too
934 ifCheckWiredInThing name
935 = do { mod <- getIfModule
936 -- Check whether we are typechecking the interface for this
937 -- very module. E.g when compiling the base library in --make mode
938 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
939 -- the HPT, so without the test we'll demand-load it into the PIT!
940 -- C.f. the same test in checkWiredInTyCon above
941 ; unless (mod == nameModule name)
942 (loadWiredInHomeIface name) }
944 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
945 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
946 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
947 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
948 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
949 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
950 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
951 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
952 ; return (check_tc (tyThingTyCon thing)) }
955 check_tc tc = case toIfaceTyCon tc of
957 other -> pprTrace "check_tc" (ppr tc) tc
961 -- we should be okay just returning Kind constructors without extra loading
962 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
963 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
964 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
965 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
966 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
968 -- Even though we are in an interface file, we want to make
969 -- sure the instances and RULES of this tycon are loaded
970 -- Imagine: f :: Double -> Double
971 tcWiredInTyCon :: TyCon -> IfL TyCon
972 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
975 tcIfaceClass :: Name -> IfL Class
976 tcIfaceClass name = do { thing <- tcIfaceGlobal name
977 ; return (tyThingClass thing) }
979 tcIfaceDataCon :: Name -> IfL DataCon
980 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
982 ADataCon dc -> return dc
983 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
985 tcIfaceExtId :: Name -> IfL Id
986 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
989 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
992 %************************************************************************
996 %************************************************************************
999 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1000 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1001 = do { name <- newIfaceName (mkVarOccFS fs)
1002 ; ty' <- tcIfaceType ty
1003 ; let id = mkLocalId name ty'
1004 ; extendIfaceIdEnv [id] (thing_inside id) }
1005 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1006 = bindIfaceTyVar bndr thing_inside
1008 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1009 bindIfaceBndrs [] thing_inside = thing_inside []
1010 bindIfaceBndrs (b:bs) thing_inside
1011 = bindIfaceBndr b $ \ b' ->
1012 bindIfaceBndrs bs $ \ bs' ->
1013 thing_inside (b':bs')
1015 -----------------------
1016 tcIfaceLetBndr (IfLetBndr fs ty info)
1017 = do { name <- newIfaceName (mkVarOccFS fs)
1018 ; ty' <- tcIfaceType ty
1020 NoInfo -> return (mkLocalId name ty')
1021 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1023 -- Similar to tcIdInfo, but much simpler
1024 tc_info [] = vanillaIdInfo
1025 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1026 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1027 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1028 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1029 (ppr other) (tc_info i)
1031 -----------------------
1032 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1033 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1034 = do { mod <- getIfModule
1035 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcLoc
1036 ; ty' <- tcIfaceType ty
1037 ; return (mkLocalId name ty') }
1039 -----------------------
1040 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1041 bindIfaceTyVar (occ,kind) thing_inside
1042 = do { name <- newIfaceName (mkTyVarOcc occ)
1043 ; tyvar <- mk_iface_tyvar name kind
1044 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1046 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1047 bindIfaceTyVars bndrs thing_inside
1048 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1049 ; tyvars <- TcRnMonad.zipWithM mk_iface_tyvar names kinds
1050 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1052 (occs,kinds) = unzip bndrs
1054 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1055 mk_iface_tyvar name ifKind
1056 = do { kind <- tcIfaceType ifKind
1057 ; if isCoercionKind kind then
1058 return (Var.mkCoVar name kind)
1060 return (Var.mkTyVar name kind) }