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, tcIfaceGlobal,
15 #include "HsVersions.h"
66 An IfaceDecl is populated with RdrNames, and these are not renamed to
67 Names before typechecking, because there should be no scope errors etc.
69 -- For (b) consider: f = $(...h....)
70 -- where h is imported, and calls f via an hi-boot file.
71 -- This is bad! But it is not seen as a staging error, because h
72 -- is indeed imported. We don't want the type-checker to black-hole
73 -- when simplifying and compiling the splice!
75 -- Simple solution: discard any unfolding that mentions a variable
76 -- bound in this module (and hence not yet processed).
77 -- The discarding happens when forkM finds a type error.
79 %************************************************************************
81 %* tcImportDecl is the key function for "faulting in" *
84 %************************************************************************
86 The main idea is this. We are chugging along type-checking source code, and
87 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
88 it in the EPS type envt. So it
90 2 gets the decl for GHC.Base.map
91 3 typechecks it via tcIfaceDecl
92 4 and adds it to the type env in the EPS
94 Note that DURING STEP 4, we may find that map's type mentions a type
97 Notice that for imported things we read the current version from the EPS
98 mutable variable. This is important in situations like
100 where the code that e1 expands to might import some defns that
101 also turn out to be needed by the code that e2 expands to.
104 tcImportDecl :: Name -> TcM TyThing
105 -- Entry point for *source-code* uses of importDecl
107 | Just thing <- wiredInNameTyThing_maybe name
108 = do { initIfaceTcRn (loadWiredInHomeIface name)
111 = do { traceIf (text "tcImportDecl" <+> ppr name)
112 ; mb_thing <- initIfaceTcRn (importDecl name)
114 Succeeded thing -> return thing
115 Failed err -> failWithTc err }
117 checkWiredInTyCon :: TyCon -> TcM ()
118 -- Ensure that the home module of the TyCon (and hence its instances)
119 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
120 -- in which case this is a no-op.
122 | not (isWiredInName tc_name)
125 = do { mod <- getModule
126 ; unless (mod == nameModule tc_name)
127 (initIfaceTcRn (loadWiredInHomeIface tc_name))
128 -- Don't look for (non-existent) Float.hi when
129 -- compiling Float.lhs, which mentions Float of course
130 -- A bit yukky to call initIfaceTcRn here
133 tc_name = tyConName tc
135 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
136 -- Get the TyThing for this Name from an interface file
137 -- It's not a wired-in thing -- the caller caught that
139 = ASSERT( not (isWiredInName name) )
142 -- Load the interface, which should populate the PTE
143 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
145 Failed err_msg -> return (Failed err_msg) ;
146 Succeeded iface -> do
148 -- Now look it up again; this time we should find it
150 ; case lookupTypeEnv (eps_PTE eps) name of
151 Just thing -> return (Succeeded thing)
152 Nothing -> return (Failed not_found_msg)
155 nd_doc = ptext SLIT("Need decl for") <+> ppr name
156 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
157 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
158 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
159 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
162 %************************************************************************
164 Type-checking a complete interface
166 %************************************************************************
168 Suppose we discover we don't need to recompile. Then we must type
169 check the old interface file. This is a bit different to the
170 incremental type checking we do as we suck in interface files. Instead
171 we do things similarly as when we are typechecking source decls: we
172 bring into scope the type envt for the interface all at once, using a
173 knot. Remember, the decls aren't necessarily in dependency order --
174 and even if they were, the type decls might be mutually recursive.
177 typecheckIface :: ModIface -- Get the decls from here
178 -> TcRnIf gbl lcl ModDetails
180 = initIfaceTc iface $ \ tc_env_var -> do
181 -- The tc_env_var is freshly allocated, private to
182 -- type-checking this particular interface
183 { -- Get the right set of decls and rules. If we are compiling without -O
184 -- we discard pragmas before typechecking, so that we don't "see"
185 -- information that we shouldn't. From a versioning point of view
186 -- It's not actually *wrong* to do so, but in fact GHCi is unable
187 -- to handle unboxed tuples, so it must not see unfoldings.
188 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
190 -- Typecheck the decls. This is done lazily, so that the knot-tying
191 -- within this single module work out right. In the If monad there is
192 -- no global envt for the current interface; instead, the knot is tied
193 -- through the if_rec_types field of IfGblEnv
194 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
195 ; let type_env = mkNameEnv names_w_things
196 ; writeMutVar tc_env_var type_env
198 -- Now do those rules and instances
199 ; insts <- mapM tcIfaceInst (mi_insts iface)
200 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
201 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
204 ; exports <- ifaceExportNames (mi_exports iface)
207 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
208 text "Type envt:" <+> ppr type_env])
209 ; return $ ModDetails { md_types = type_env
211 , md_fam_insts = fam_insts
213 , md_exports = exports
214 , md_dbg_sites = noDbgSites
220 %************************************************************************
222 Type and class declarations
224 %************************************************************************
227 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
228 -- Load the hi-boot iface for the module being compiled,
229 -- if it indeed exists in the transitive closure of imports
230 -- Return the ModDetails, empty if no hi-boot iface
231 tcHiBootIface hsc_src mod
232 | isHsBoot hsc_src -- Already compiling a hs-boot file
233 = return emptyModDetails
235 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
238 ; if not (isOneShot mode)
239 -- In --make and interactive mode, if this module has an hs-boot file
240 -- we'll have compiled it already, and it'll be in the HPT
242 -- We check wheher the interface is a *boot* interface.
243 -- It can happen (when using GHC from Visual Studio) that we
244 -- compile a module in TypecheckOnly mode, with a stable,
245 -- fully-populated HPT. In that case the boot interface isn't there
246 -- (it's been replaced by the mother module) so we can't check it.
247 -- And that's fine, because if M's ModInfo is in the HPT, then
248 -- it's been compiled once, and we don't need to check the boot iface
249 then do { hpt <- getHpt
250 ; case lookupUFM hpt (moduleName mod) of
251 Just info | mi_boot (hm_iface info)
252 -> return (hm_details info)
253 other -> return emptyModDetails }
256 -- OK, so we're in one-shot mode.
257 -- In that case, we're read all the direct imports by now,
258 -- so eps_is_boot will record if any of our imports mention us by
259 -- way of hi-boot file
261 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
262 Nothing -> return emptyModDetails ; -- The typical case
264 Just (_, False) -> failWithTc moduleLoop ;
265 -- Someone below us imported us!
266 -- This is a loop with no hi-boot in the way
268 Just (_mod, True) -> -- There's a hi-boot interface below us
270 do { read_result <- findAndReadIface
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 :: Bool -- True <=> discard IdInfo on IfaceId bindings
345 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
346 = do { name <- lookupIfaceTop occ_name
347 ; ty <- tcIfaceType iface_type
348 ; info <- tcIdInfo ignore_prags name ty info
349 ; return (AnId (mkVanillaGlobal name ty info)) }
351 tcIfaceDecl ignore_prags
352 (IfaceData {ifName = occ_name,
354 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
357 ifGeneric = want_generic,
358 ifFamInst = mb_family })
359 = do { tc_name <- lookupIfaceTop occ_name
360 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
362 { tycon <- fixM ( \ tycon -> do
363 { stupid_theta <- tcIfaceCtxt ctxt
366 Nothing -> return Nothing
368 do { famTyCon <- tcIfaceTyCon fam
369 ; insttys <- mapM tcIfaceType tys
370 ; return $ Just (famTyCon, insttys)
372 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
373 ; buildAlgTyCon tc_name tyvars stupid_theta
374 cons is_rec want_generic gadt_syn famInst
376 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
377 ; return (ATyCon tycon)
380 tcIfaceDecl ignore_prags
381 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
382 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
383 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
384 { tc_name <- lookupIfaceTop occ_name
385 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
386 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
387 else SynonymTyCon rhs_tyki
388 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs))
391 tcIfaceDecl ignore_prags
392 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
393 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
394 ifATs = rdr_ats, ifSigs = rdr_sigs,
396 -- ToDo: in hs-boot files we should really treat abstract classes specially,
397 -- as we do abstract tycons
398 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
399 { cls_name <- lookupIfaceTop occ_name
400 ; ctxt <- tcIfaceCtxt rdr_ctxt
401 ; sigs <- mappM tc_sig rdr_sigs
402 ; fds <- mappM tc_fd rdr_fds
403 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
404 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
405 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
406 ; return (AClass cls) }
408 tc_sig (IfaceClassOp occ dm rdr_ty)
409 = do { op_name <- lookupIfaceTop occ
410 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
411 -- Must be done lazily for just the same reason as the
412 -- type of a data con; to avoid sucking in types that
413 -- it mentions unless it's necessray to do so
414 ; return (op_name, dm, op_ty) }
416 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
418 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
419 ; tvs2' <- mappM tcIfaceTyVar tvs2
420 ; return (tvs1', tvs2') }
422 -- For each AT argument compute the position of the corresponding class
423 -- parameter in the class head. This will later serve as a permutation
424 -- vector when checking the validity of instance declarations.
425 setTyThingPoss (ATyCon tycon) atTyVars =
426 let classTyVars = map fst tv_bndrs
428 . map ((`elemIndex` classTyVars) . fst)
430 -- There will be no Nothing, as we already passed renaming
432 ATyCon (setTyConArgPoss tycon poss)
433 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
435 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
436 = do { name <- lookupIfaceTop rdr_name
437 ; return (ATyCon (mkForeignTyCon name ext_name
440 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
442 IfAbstractTyCon -> return mkAbstractTyConRhs
443 IfOpenDataTyCon -> return mkOpenDataTyConRhs
444 IfOpenNewTyCon -> return mkOpenNewTyConRhs
445 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
446 ; return (mkDataTyConRhs data_cons) }
447 IfNewTyCon con -> do { data_con <- tc_con_decl con
448 ; mkNewTyConRhs tycon_name tycon data_con }
450 tc_con_decl (IfCon { ifConInfix = is_infix,
451 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
452 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
453 ifConArgTys = args, ifConFields = field_lbls,
454 ifConStricts = stricts})
455 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
456 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
457 { name <- lookupIfaceTop occ
458 ; eq_spec <- tcIfaceEqSpec spec
459 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
460 -- At one stage I thought that this context checking *had*
461 -- to be lazy, because of possible mutual recursion between the
462 -- type and the classe:
464 -- class Real a where { toRat :: a -> Ratio Integer }
465 -- data (Real a) => Ratio a = ...
466 -- But now I think that the laziness in checking class ops breaks
467 -- the loop, so no laziness needed
469 -- Read the argument types, but lazily to avoid faulting in
470 -- the component types unless they are really needed
471 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
472 ; lbl_names <- mappM lookupIfaceTop field_lbls
474 ; buildDataCon name is_infix {- Not infix -}
476 univ_tyvars ex_tyvars
480 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
485 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
486 ; ty <- tcIfaceType if_ty
491 %************************************************************************
495 %************************************************************************
498 tcIfaceInst :: IfaceInst -> IfL Instance
499 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
500 ifInstCls = cls, ifInstTys = mb_tcs,
502 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
503 tcIfaceExtId dfun_occ
504 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
505 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
507 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
508 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
509 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
510 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
511 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
512 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
514 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
515 ; return (mkImportedFamInst fam mb_tcs' tycon') }
519 %************************************************************************
523 %************************************************************************
525 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
526 are in the type environment. However, remember that typechecking a Rule may
527 (as a side effect) augment the type envt, and so we may need to iterate the process.
530 tcIfaceRules :: Bool -- True <=> ignore rules
533 tcIfaceRules ignore_prags if_rules
534 | ignore_prags = return []
535 | otherwise = mapM tcIfaceRule if_rules
537 tcIfaceRule :: IfaceRule -> IfL CoreRule
538 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
539 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
541 = do { ~(bndrs', args', rhs') <-
542 -- Typecheck the payload lazily, in the hope it'll never be looked at
543 forkM (ptext SLIT("Rule") <+> ftext name) $
544 bindIfaceBndrs bndrs $ \ bndrs' ->
545 do { args' <- mappM tcIfaceExpr args
546 ; rhs' <- tcIfaceExpr rhs
547 ; return (bndrs', args', rhs') }
548 ; let mb_tcs = map ifTopFreeName args
550 ; returnM (Rule { ru_name = name, ru_fn = fn, ru_act = act,
551 ru_bndrs = bndrs', ru_args = args',
554 ru_local = False }) } -- An imported RULE is never for a local Id
555 -- or, even if it is (module loop, perhaps)
556 -- we'll just leave it in the non-local set
558 -- This function *must* mirror exactly what Rules.topFreeName does
559 -- We could have stored the ru_rough field in the iface file
560 -- but that would be redundant, I think.
561 -- The only wrinkle is that we must not be deceived by
562 -- type syononyms at the top of a type arg. Since
563 -- we can't tell at this point, we are careful not
564 -- to write them out in coreRuleToIfaceRule
565 ifTopFreeName :: IfaceExpr -> Maybe Name
566 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
567 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
568 ifTopFreeName (IfaceExt n) = Just n
569 ifTopFreeName other = Nothing
573 %************************************************************************
577 %************************************************************************
580 tcIfaceType :: IfaceType -> IfL Type
581 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
582 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
583 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
584 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
585 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
586 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
588 tcIfaceTypes tys = mapM tcIfaceType tys
590 -----------------------------------------
591 tcIfacePredType :: IfacePredType -> IfL PredType
592 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
593 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
594 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
596 -----------------------------------------
597 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
598 tcIfaceCtxt sts = mappM tcIfacePredType sts
602 %************************************************************************
606 %************************************************************************
609 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
610 tcIfaceExpr (IfaceType ty)
611 = tcIfaceType ty `thenM` \ ty' ->
614 tcIfaceExpr (IfaceLcl name)
615 = tcIfaceLclId name `thenM` \ id ->
618 tcIfaceExpr (IfaceExt gbl)
619 = tcIfaceExtId gbl `thenM` \ id ->
622 tcIfaceExpr (IfaceLit lit)
625 tcIfaceExpr (IfaceFCall cc ty)
626 = tcIfaceType ty `thenM` \ ty' ->
627 newUnique `thenM` \ u ->
628 returnM (Var (mkFCallId u cc ty'))
630 tcIfaceExpr (IfaceTuple boxity args)
631 = mappM tcIfaceExpr args `thenM` \ args' ->
633 -- Put the missing type arguments back in
634 con_args = map (Type . exprType) args' ++ args'
636 returnM (mkApps (Var con_id) con_args)
639 con_id = dataConWorkId (tupleCon boxity arity)
642 tcIfaceExpr (IfaceLam bndr body)
643 = bindIfaceBndr bndr $ \ bndr' ->
644 tcIfaceExpr body `thenM` \ body' ->
645 returnM (Lam bndr' body')
647 tcIfaceExpr (IfaceApp fun arg)
648 = tcIfaceExpr fun `thenM` \ fun' ->
649 tcIfaceExpr arg `thenM` \ arg' ->
650 returnM (App fun' arg')
652 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
653 = tcIfaceExpr scrut `thenM` \ scrut' ->
654 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
656 scrut_ty = exprType scrut'
657 case_bndr' = mkLocalId case_bndr_name scrut_ty
658 tc_app = splitTyConApp scrut_ty
659 -- NB: Won't always succeed (polymoprhic case)
660 -- but won't be demanded in those cases
661 -- NB: not tcSplitTyConApp; we are looking at Core here
662 -- look through non-rec newtypes to find the tycon that
663 -- corresponds to the datacon in this case alternative
665 extendIfaceIdEnv [case_bndr'] $
666 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
667 tcIfaceType ty `thenM` \ ty' ->
668 returnM (Case scrut' case_bndr' ty' alts')
670 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
671 = tcIfaceExpr rhs `thenM` \ rhs' ->
672 bindIfaceId bndr $ \ bndr' ->
673 tcIfaceExpr body `thenM` \ body' ->
674 returnM (Let (NonRec bndr' rhs') body')
676 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
677 = bindIfaceIds bndrs $ \ bndrs' ->
678 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
679 tcIfaceExpr body `thenM` \ body' ->
680 returnM (Let (Rec (bndrs' `zip` rhss')) body')
682 (bndrs, rhss) = unzip pairs
684 tcIfaceExpr (IfaceCast expr co) = do
685 expr' <- tcIfaceExpr expr
686 co' <- tcIfaceType co
687 returnM (Cast expr' co')
689 tcIfaceExpr (IfaceNote note expr)
690 = tcIfaceExpr expr `thenM` \ expr' ->
692 IfaceInlineMe -> returnM (Note InlineMe expr')
693 IfaceSCC cc -> returnM (Note (SCC cc) expr')
694 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
696 -------------------------
697 tcIfaceAlt _ (IfaceDefault, names, rhs)
698 = ASSERT( null names )
699 tcIfaceExpr rhs `thenM` \ rhs' ->
700 returnM (DEFAULT, [], rhs')
702 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
703 = ASSERT( null names )
704 tcIfaceExpr rhs `thenM` \ rhs' ->
705 returnM (LitAlt lit, [], rhs')
707 -- A case alternative is made quite a bit more complicated
708 -- by the fact that we omit type annotations because we can
709 -- work them out. True enough, but its not that easy!
710 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
711 = do { con <- tcIfaceDataCon data_occ
712 ; ASSERT2( con `elem` tyConDataCons tycon,
713 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
714 tcIfaceDataAlt con inst_tys arg_strs rhs }
716 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
717 = ASSERT( isTupleTyCon tycon )
718 do { let [data_con] = tyConDataCons tycon
719 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
721 tcIfaceDataAlt con inst_tys arg_strs rhs
722 = do { us <- newUniqueSupply
723 ; let uniqs = uniqsFromSupply us
724 ; let (ex_tvs, co_tvs, arg_ids)
725 = dataConRepFSInstPat arg_strs uniqs con inst_tys
726 all_tvs = ex_tvs ++ co_tvs
728 ; rhs' <- extendIfaceTyVarEnv all_tvs $
729 extendIfaceIdEnv arg_ids $
731 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
736 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
737 tcExtCoreBindings [] = return []
738 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
740 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
741 do_one (IfaceNonRec bndr rhs) thing_inside
742 = do { rhs' <- tcIfaceExpr rhs
743 ; bndr' <- newExtCoreBndr bndr
744 ; extendIfaceIdEnv [bndr'] $ do
745 { core_binds <- thing_inside
746 ; return (NonRec bndr' rhs' : core_binds) }}
748 do_one (IfaceRec pairs) thing_inside
749 = do { bndrs' <- mappM newExtCoreBndr bndrs
750 ; extendIfaceIdEnv bndrs' $ do
751 { rhss' <- mappM tcIfaceExpr rhss
752 ; core_binds <- thing_inside
753 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
755 (bndrs,rhss) = unzip pairs
759 %************************************************************************
763 %************************************************************************
766 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
767 tcIdInfo ignore_prags name ty info
768 | ignore_prags = return vanillaIdInfo
769 | otherwise = case info of
770 NoInfo -> return vanillaIdInfo
771 HasInfo info -> foldlM tcPrag init_info info
773 -- Set the CgInfo to something sensible but uninformative before
774 -- we start; default assumption is that it has CAFs
775 init_info = vanillaIdInfo
777 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
778 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
779 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
781 -- The next two are lazy, so they don't transitively suck stuff in
782 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
783 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
784 tcPrag info (HsUnfold expr)
785 = tcPragExpr name expr `thenM` \ maybe_expr' ->
787 -- maybe_expr' doesn't get looked at if the unfolding
788 -- is never inspected; so the typecheck doesn't even happen
789 unfold_info = case maybe_expr' of
790 Nothing -> noUnfolding
791 Just expr' -> mkTopUnfolding expr'
793 returnM (info `setUnfoldingInfoLazily` unfold_info)
797 tcWorkerInfo ty info wkr arity
798 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
800 -- We return without testing maybe_wkr_id, but as soon as info is
801 -- looked at we will test it. That's ok, because its outside the
802 -- knot; and there seems no big reason to further defer the
803 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
804 -- over the unfolding until it's actually used does seem worth while.)
805 ; us <- newUniqueSupply
807 ; returnM (case mb_wkr_id of
809 Just wkr_id -> add_wkr_info us wkr_id info) }
811 doc = text "Worker for" <+> ppr wkr
812 add_wkr_info us wkr_id info
813 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
814 `setWorkerInfo` HasWorker wkr_id arity
816 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
818 -- We are relying here on strictness info always appearing
819 -- before worker info, fingers crossed ....
820 strict_sig = case newStrictnessInfo info of
822 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
825 For unfoldings we try to do the job lazily, so that we never type check
826 an unfolding that isn't going to be looked at.
829 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
832 tcIfaceExpr expr `thenM` \ core_expr' ->
834 -- Check for type consistency in the unfolding
835 ifOptM Opt_DoCoreLinting (
836 get_in_scope_ids `thenM` \ in_scope ->
837 case lintUnfolding noSrcLoc in_scope core_expr' of
838 Nothing -> returnM ()
839 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
844 doc = text "Unfolding of" <+> ppr name
845 get_in_scope_ids -- Urgh; but just for linting
847 do { env <- getGblEnv
848 ; case if_rec_types env of {
849 Nothing -> return [] ;
850 Just (_, get_env) -> do
851 { type_env <- get_env
852 ; return (typeEnvIds type_env) }}}
857 %************************************************************************
859 Getting from Names to TyThings
861 %************************************************************************
864 tcIfaceGlobal :: Name -> IfL TyThing
866 | Just thing <- wiredInNameTyThing_maybe name
867 -- Wired-in things include TyCons, DataCons, and Ids
868 = do { ifCheckWiredInThing name; return thing }
870 = do { (eps,hpt) <- getEpsAndHpt
872 ; case lookupType dflags hpt (eps_PTE eps) name of {
873 Just thing -> return thing ;
877 ; case if_rec_types env of {
878 Just (mod, get_type_env)
879 | nameIsLocalOrFrom mod name
880 -> do -- It's defined in the module being compiled
881 { type_env <- setLclEnv () get_type_env -- yuk
882 ; case lookupNameEnv type_env name of
883 Just thing -> return thing
884 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
885 (ppr name $$ ppr type_env) }
889 { mb_thing <- importDecl name -- It's imported; go get it
891 Failed err -> failIfM err
892 Succeeded thing -> return thing
895 ifCheckWiredInThing :: Name -> IfL ()
896 -- Even though we are in an interface file, we want to make
897 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
898 -- Ditto want to ensure that RULES are loaded too
899 ifCheckWiredInThing name
900 = do { mod <- getIfModule
901 -- Check whether we are typechecking the interface for this
902 -- very module. E.g when compiling the base library in --make mode
903 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
904 -- the HPT, so without the test we'll demand-load it into the PIT!
905 -- C.f. the same test in checkWiredInTyCon above
906 ; unless (mod == nameModule name)
907 (loadWiredInHomeIface name) }
909 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
910 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
911 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
912 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
913 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
914 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
915 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
916 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
917 ; return (check_tc (tyThingTyCon thing)) }
920 check_tc tc = case toIfaceTyCon tc of
922 other -> pprTrace "check_tc" (ppr tc) tc
926 -- we should be okay just returning Kind constructors without extra loading
927 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
928 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
929 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
930 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
931 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
933 -- Even though we are in an interface file, we want to make
934 -- sure the instances and RULES of this tycon are loaded
935 -- Imagine: f :: Double -> Double
936 tcWiredInTyCon :: TyCon -> IfL TyCon
937 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
940 tcIfaceClass :: Name -> IfL Class
941 tcIfaceClass name = do { thing <- tcIfaceGlobal name
942 ; return (tyThingClass thing) }
944 tcIfaceDataCon :: Name -> IfL DataCon
945 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
947 ADataCon dc -> return dc
948 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
950 tcIfaceExtId :: Name -> IfL Id
951 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
954 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
957 %************************************************************************
961 %************************************************************************
964 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
965 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
966 = bindIfaceId bndr thing_inside
967 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
968 = bindIfaceTyVar bndr thing_inside
970 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
971 bindIfaceBndrs [] thing_inside = thing_inside []
972 bindIfaceBndrs (b:bs) thing_inside
973 = bindIfaceBndr b $ \ b' ->
974 bindIfaceBndrs bs $ \ bs' ->
975 thing_inside (b':bs')
977 -----------------------
978 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
979 bindIfaceId (occ, ty) thing_inside
980 = do { name <- newIfaceName (mkVarOccFS occ)
981 ; ty' <- tcIfaceType ty
982 ; let { id = mkLocalId name ty' }
983 ; extendIfaceIdEnv [id] (thing_inside id) }
985 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
986 bindIfaceIds bndrs thing_inside
987 = do { names <- newIfaceNames (map mkVarOccFS occs)
988 ; tys' <- mappM tcIfaceType tys
989 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
990 ; extendIfaceIdEnv ids (thing_inside ids) }
992 (occs,tys) = unzip bndrs
995 -----------------------
996 newExtCoreBndr :: IfaceIdBndr -> IfL Id
997 newExtCoreBndr (var, ty)
998 = do { mod <- getIfModule
999 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcLoc
1000 ; ty' <- tcIfaceType ty
1001 ; return (mkLocalId name ty') }
1003 -----------------------
1004 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1005 bindIfaceTyVar (occ,kind) thing_inside
1006 = do { name <- newIfaceName (mkTyVarOcc occ)
1007 ; tyvar <- mk_iface_tyvar name kind
1008 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1010 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1011 bindIfaceTyVars bndrs thing_inside
1012 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1013 ; tyvars <- TcRnMonad.zipWithM mk_iface_tyvar names kinds
1014 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1016 (occs,kinds) = unzip bndrs
1018 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1019 mk_iface_tyvar name ifKind
1020 = do { kind <- tcIfaceType ifKind
1021 ; if isCoercionKind kind then
1022 return (Var.mkCoVar name kind)
1024 return (Var.mkTyVar name kind) }