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"
64 An IfaceDecl is populated with RdrNames, and these are not renamed to
65 Names before typechecking, because there should be no scope errors etc.
67 -- For (b) consider: f = $(...h....)
68 -- where h is imported, and calls f via an hi-boot file.
69 -- This is bad! But it is not seen as a staging error, because h
70 -- is indeed imported. We don't want the type-checker to black-hole
71 -- when simplifying and compiling the splice!
73 -- Simple solution: discard any unfolding that mentions a variable
74 -- bound in this module (and hence not yet processed).
75 -- The discarding happens when forkM finds a type error.
77 %************************************************************************
79 %* tcImportDecl is the key function for "faulting in" *
82 %************************************************************************
84 The main idea is this. We are chugging along type-checking source code, and
85 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
86 it in the EPS type envt. So it
88 2 gets the decl for GHC.Base.map
89 3 typechecks it via tcIfaceDecl
90 4 and adds it to the type env in the EPS
92 Note that DURING STEP 4, we may find that map's type mentions a type
95 Notice that for imported things we read the current version from the EPS
96 mutable variable. This is important in situations like
98 where the code that e1 expands to might import some defns that
99 also turn out to be needed by the code that e2 expands to.
102 tcImportDecl :: Name -> TcM TyThing
103 -- Entry point for *source-code* uses of importDecl
105 | Just thing <- wiredInNameTyThing_maybe name
106 = do { initIfaceTcRn (loadWiredInHomeIface name)
109 = do { traceIf (text "tcImportDecl" <+> ppr name)
110 ; mb_thing <- initIfaceTcRn (importDecl name)
112 Succeeded thing -> return thing
113 Failed err -> failWithTc err }
115 checkWiredInTyCon :: TyCon -> TcM ()
116 -- Ensure that the home module of the TyCon (and hence its instances)
117 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
118 -- in which case this is a no-op.
120 | not (isWiredInName tc_name)
123 = do { mod <- getModule
124 ; unless (mod == nameModule tc_name)
125 (initIfaceTcRn (loadWiredInHomeIface tc_name))
126 -- Don't look for (non-existent) Float.hi when
127 -- compiling Float.lhs, which mentions Float of course
128 -- A bit yukky to call initIfaceTcRn here
131 tc_name = tyConName tc
133 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
134 -- Get the TyThing for this Name from an interface file
135 -- It's not a wired-in thing -- the caller caught that
137 = ASSERT( not (isWiredInName name) )
140 -- Load the interface, which should populate the PTE
141 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
143 Failed err_msg -> return (Failed err_msg) ;
144 Succeeded iface -> do
146 -- Now look it up again; this time we should find it
148 ; case lookupTypeEnv (eps_PTE eps) name of
149 Just thing -> return (Succeeded thing)
150 Nothing -> return (Failed not_found_msg)
153 nd_doc = ptext SLIT("Need decl for") <+> ppr name
154 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
155 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
156 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
157 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
160 %************************************************************************
162 Type-checking a complete interface
164 %************************************************************************
166 Suppose we discover we don't need to recompile. Then we must type
167 check the old interface file. This is a bit different to the
168 incremental type checking we do as we suck in interface files. Instead
169 we do things similarly as when we are typechecking source decls: we
170 bring into scope the type envt for the interface all at once, using a
171 knot. Remember, the decls aren't necessarily in dependency order --
172 and even if they were, the type decls might be mutually recursive.
175 typecheckIface :: ModIface -- Get the decls from here
176 -> TcRnIf gbl lcl ModDetails
178 = initIfaceTc iface $ \ tc_env_var -> do
179 -- The tc_env_var is freshly allocated, private to
180 -- type-checking this particular interface
181 { -- Get the right set of decls and rules. If we are compiling without -O
182 -- we discard pragmas before typechecking, so that we don't "see"
183 -- information that we shouldn't. From a versioning point of view
184 -- It's not actually *wrong* to do so, but in fact GHCi is unable
185 -- to handle unboxed tuples, so it must not see unfoldings.
186 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
188 -- Typecheck the decls. This is done lazily, so that the knot-tying
189 -- within this single module work out right. In the If monad there is
190 -- no global envt for the current interface; instead, the knot is tied
191 -- through the if_rec_types field of IfGblEnv
192 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
193 ; let type_env = mkNameEnv names_w_things
194 ; writeMutVar tc_env_var type_env
196 -- Now do those rules and instances
197 ; insts <- mapM tcIfaceInst (mi_insts iface)
198 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
199 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
202 ; exports <- ifaceExportNames (mi_exports iface)
205 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
206 text "Type envt:" <+> ppr type_env])
207 ; return $ ModDetails { md_types = type_env
209 , md_fam_insts = fam_insts
211 , md_exports = exports
212 , md_modBreaks = emptyModBreaks
218 %************************************************************************
220 Type and class declarations
222 %************************************************************************
225 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
226 -- Load the hi-boot iface for the module being compiled,
227 -- if it indeed exists in the transitive closure of imports
228 -- Return the ModDetails, empty if no hi-boot iface
229 tcHiBootIface hsc_src mod
230 | isHsBoot hsc_src -- Already compiling a hs-boot file
231 = return emptyModDetails
233 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
236 ; if not (isOneShot mode)
237 -- In --make and interactive mode, if this module has an hs-boot file
238 -- we'll have compiled it already, and it'll be in the HPT
240 -- We check wheher the interface is a *boot* interface.
241 -- It can happen (when using GHC from Visual Studio) that we
242 -- compile a module in TypecheckOnly mode, with a stable,
243 -- fully-populated HPT. In that case the boot interface isn't there
244 -- (it's been replaced by the mother module) so we can't check it.
245 -- And that's fine, because if M's ModInfo is in the HPT, then
246 -- it's been compiled once, and we don't need to check the boot iface
247 then do { hpt <- getHpt
248 ; case lookupUFM hpt (moduleName mod) of
249 Just info | mi_boot (hm_iface info)
250 -> return (hm_details info)
251 other -> return emptyModDetails }
254 -- OK, so we're in one-shot mode.
255 -- In that case, we're read all the direct imports by now,
256 -- so eps_is_boot will record if any of our imports mention us by
257 -- way of hi-boot file
259 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
260 Nothing -> return emptyModDetails ; -- The typical case
262 Just (_, False) -> failWithTc moduleLoop ;
263 -- Someone below us imported us!
264 -- This is a loop with no hi-boot in the way
266 Just (_mod, True) -> -- There's a hi-boot interface below us
268 do { read_result <- findAndReadIface
272 ; case read_result of
273 Failed err -> failWithTc (elaborate err)
274 Succeeded (iface, _path) -> typecheckIface iface
277 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
278 <+> ptext SLIT("to compare against the Real Thing")
280 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
281 <+> ptext SLIT("depends on itself")
283 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
284 quotes (ppr mod) <> colon) 4 err
288 %************************************************************************
290 Type and class declarations
292 %************************************************************************
294 When typechecking a data type decl, we *lazily* (via forkM) typecheck
295 the constructor argument types. This is in the hope that we may never
296 poke on those argument types, and hence may never need to load the
297 interface files for types mentioned in the arg types.
300 data Foo.S = MkS Baz.T
301 Mabye we can get away without even loading the interface for Baz!
303 This is not just a performance thing. Suppose we have
304 data Foo.S = MkS Baz.T
305 data Baz.T = MkT Foo.S
306 (in different interface files, of course).
307 Now, first we load and typecheck Foo.S, and add it to the type envt.
308 If we do explore MkS's argument, we'll load and typecheck Baz.T.
309 If we explore MkT's argument we'll find Foo.S already in the envt.
311 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
312 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
313 which isn't done yet.
315 All very cunning. However, there is a rather subtle gotcha which bit
316 me when developing this stuff. When we typecheck the decl for S, we
317 extend the type envt with S, MkS, and all its implicit Ids. Suppose
318 (a bug, but it happened) that the list of implicit Ids depended in
319 turn on the constructor arg types. Then the following sequence of
321 * we build a thunk <t> for the constructor arg tys
322 * we build a thunk for the extended type environment (depends on <t>)
323 * we write the extended type envt into the global EPS mutvar
325 Now we look something up in the type envt
327 * which reads the global type envt out of the global EPS mutvar
328 * but that depends in turn on <t>
330 It's subtle, because, it'd work fine if we typechecked the constructor args
331 eagerly -- they don't need the extended type envt. They just get the extended
332 type envt by accident, because they look at it later.
334 What this means is that the implicitTyThings MUST NOT DEPEND on any of
339 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
343 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
344 = do { name <- lookupIfaceTop occ_name
345 ; ty <- tcIfaceType iface_type
346 ; info <- tcIdInfo ignore_prags name ty info
347 ; return (AnId (mkVanillaGlobal name ty info)) }
349 tcIfaceDecl ignore_prags
350 (IfaceData {ifName = occ_name,
352 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
355 ifGeneric = want_generic,
356 ifFamInst = mb_family })
357 = do { tc_name <- lookupIfaceTop occ_name
358 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
360 { tycon <- fixM ( \ tycon -> do
361 { stupid_theta <- tcIfaceCtxt ctxt
364 Nothing -> return Nothing
366 do { famTyCon <- tcIfaceTyCon fam
367 ; insttys <- mapM tcIfaceType tys
368 ; return $ Just (famTyCon, insttys)
370 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
371 ; buildAlgTyCon tc_name tyvars stupid_theta
372 cons is_rec want_generic gadt_syn famInst
374 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
375 ; return (ATyCon tycon)
378 tcIfaceDecl ignore_prags
379 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
380 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
381 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
382 { tc_name <- lookupIfaceTop occ_name
383 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
384 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
385 else SynonymTyCon rhs_tyki
386 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs))
389 tcIfaceDecl ignore_prags
390 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
391 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
392 ifATs = rdr_ats, ifSigs = rdr_sigs,
394 -- ToDo: in hs-boot files we should really treat abstract classes specially,
395 -- as we do abstract tycons
396 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
397 { cls_name <- lookupIfaceTop occ_name
398 ; ctxt <- tcIfaceCtxt rdr_ctxt
399 ; sigs <- mappM tc_sig rdr_sigs
400 ; fds <- mappM tc_fd rdr_fds
401 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
402 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
403 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
404 ; return (AClass cls) }
406 tc_sig (IfaceClassOp occ dm rdr_ty)
407 = do { op_name <- lookupIfaceTop occ
408 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
409 -- Must be done lazily for just the same reason as the
410 -- type of a data con; to avoid sucking in types that
411 -- it mentions unless it's necessray to do so
412 ; return (op_name, dm, op_ty) }
414 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
416 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
417 ; tvs2' <- mappM tcIfaceTyVar tvs2
418 ; return (tvs1', tvs2') }
420 -- For each AT argument compute the position of the corresponding class
421 -- parameter in the class head. This will later serve as a permutation
422 -- vector when checking the validity of instance declarations.
423 setTyThingPoss (ATyCon tycon) atTyVars =
424 let classTyVars = map fst tv_bndrs
426 . map ((`elemIndex` classTyVars) . fst)
428 -- There will be no Nothing, as we already passed renaming
430 ATyCon (setTyConArgPoss tycon poss)
431 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
433 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
434 = do { name <- lookupIfaceTop rdr_name
435 ; return (ATyCon (mkForeignTyCon name ext_name
438 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
440 IfAbstractTyCon -> return mkAbstractTyConRhs
441 IfOpenDataTyCon -> return mkOpenDataTyConRhs
442 IfOpenNewTyCon -> return mkOpenNewTyConRhs
443 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
444 ; return (mkDataTyConRhs data_cons) }
445 IfNewTyCon con -> do { data_con <- tc_con_decl con
446 ; mkNewTyConRhs tycon_name tycon data_con }
448 tc_con_decl (IfCon { ifConInfix = is_infix,
449 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
450 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
451 ifConArgTys = args, ifConFields = field_lbls,
452 ifConStricts = stricts})
453 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
454 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
455 { name <- lookupIfaceTop occ
456 ; eq_spec <- tcIfaceEqSpec spec
457 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
458 -- At one stage I thought that this context checking *had*
459 -- to be lazy, because of possible mutual recursion between the
460 -- type and the classe:
462 -- class Real a where { toRat :: a -> Ratio Integer }
463 -- data (Real a) => Ratio a = ...
464 -- But now I think that the laziness in checking class ops breaks
465 -- the loop, so no laziness needed
467 -- Read the argument types, but lazily to avoid faulting in
468 -- the component types unless they are really needed
469 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
470 ; lbl_names <- mappM lookupIfaceTop field_lbls
472 ; buildDataCon name is_infix {- Not infix -}
474 univ_tyvars ex_tyvars
478 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
483 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
484 ; ty <- tcIfaceType if_ty
489 %************************************************************************
493 %************************************************************************
496 tcIfaceInst :: IfaceInst -> IfL Instance
497 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
498 ifInstCls = cls, ifInstTys = mb_tcs,
500 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
501 tcIfaceExtId dfun_occ
502 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
503 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
505 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
506 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
507 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
508 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
509 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
510 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
512 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
513 ; return (mkImportedFamInst fam mb_tcs' tycon') }
517 %************************************************************************
521 %************************************************************************
523 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
524 are in the type environment. However, remember that typechecking a Rule may
525 (as a side effect) augment the type envt, and so we may need to iterate the process.
528 tcIfaceRules :: Bool -- True <=> ignore rules
531 tcIfaceRules ignore_prags if_rules
532 | ignore_prags = return []
533 | otherwise = mapM tcIfaceRule if_rules
535 tcIfaceRule :: IfaceRule -> IfL CoreRule
536 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
537 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
539 = do { ~(bndrs', args', rhs') <-
540 -- Typecheck the payload lazily, in the hope it'll never be looked at
541 forkM (ptext SLIT("Rule") <+> ftext name) $
542 bindIfaceBndrs bndrs $ \ bndrs' ->
543 do { args' <- mappM tcIfaceExpr args
544 ; rhs' <- tcIfaceExpr rhs
545 ; return (bndrs', args', rhs') }
546 ; let mb_tcs = map ifTopFreeName args
548 ; returnM (Rule { ru_name = name, ru_fn = fn, ru_act = act,
549 ru_bndrs = bndrs', ru_args = args',
552 ru_local = False }) } -- An imported RULE is never for a local Id
553 -- or, even if it is (module loop, perhaps)
554 -- we'll just leave it in the non-local set
556 -- This function *must* mirror exactly what Rules.topFreeName does
557 -- We could have stored the ru_rough field in the iface file
558 -- but that would be redundant, I think.
559 -- The only wrinkle is that we must not be deceived by
560 -- type syononyms at the top of a type arg. Since
561 -- we can't tell at this point, we are careful not
562 -- to write them out in coreRuleToIfaceRule
563 ifTopFreeName :: IfaceExpr -> Maybe Name
564 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
565 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
566 ifTopFreeName (IfaceExt n) = Just n
567 ifTopFreeName other = Nothing
571 %************************************************************************
575 %************************************************************************
578 tcIfaceType :: IfaceType -> IfL Type
579 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
580 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
581 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
582 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
583 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
584 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
586 tcIfaceTypes tys = mapM tcIfaceType tys
588 -----------------------------------------
589 tcIfacePredType :: IfacePredType -> IfL PredType
590 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
591 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
592 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
594 -----------------------------------------
595 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
596 tcIfaceCtxt sts = mappM tcIfacePredType sts
600 %************************************************************************
604 %************************************************************************
607 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
608 tcIfaceExpr (IfaceType ty)
609 = tcIfaceType ty `thenM` \ ty' ->
612 tcIfaceExpr (IfaceLcl name)
613 = tcIfaceLclId name `thenM` \ id ->
616 tcIfaceExpr (IfaceExt gbl)
617 = tcIfaceExtId gbl `thenM` \ id ->
620 tcIfaceExpr (IfaceLit lit)
623 tcIfaceExpr (IfaceFCall cc ty)
624 = tcIfaceType ty `thenM` \ ty' ->
625 newUnique `thenM` \ u ->
626 returnM (Var (mkFCallId u cc ty'))
628 tcIfaceExpr (IfaceTuple boxity args)
629 = mappM tcIfaceExpr args `thenM` \ args' ->
631 -- Put the missing type arguments back in
632 con_args = map (Type . exprType) args' ++ args'
634 returnM (mkApps (Var con_id) con_args)
637 con_id = dataConWorkId (tupleCon boxity arity)
640 tcIfaceExpr (IfaceLam bndr body)
641 = bindIfaceBndr bndr $ \ bndr' ->
642 tcIfaceExpr body `thenM` \ body' ->
643 returnM (Lam bndr' body')
645 tcIfaceExpr (IfaceApp fun arg)
646 = tcIfaceExpr fun `thenM` \ fun' ->
647 tcIfaceExpr arg `thenM` \ arg' ->
648 returnM (App fun' arg')
650 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
651 = tcIfaceExpr scrut `thenM` \ scrut' ->
652 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
654 scrut_ty = exprType scrut'
655 case_bndr' = mkLocalId case_bndr_name scrut_ty
656 tc_app = splitTyConApp scrut_ty
657 -- NB: Won't always succeed (polymoprhic case)
658 -- but won't be demanded in those cases
659 -- NB: not tcSplitTyConApp; we are looking at Core here
660 -- look through non-rec newtypes to find the tycon that
661 -- corresponds to the datacon in this case alternative
663 extendIfaceIdEnv [case_bndr'] $
664 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
665 tcIfaceType ty `thenM` \ ty' ->
666 returnM (Case scrut' case_bndr' ty' alts')
668 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
669 = do { rhs' <- tcIfaceExpr rhs
670 ; id <- tcIfaceLetBndr bndr
671 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
672 ; return (Let (NonRec id rhs') body') }
674 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
675 = do { ids <- mapM tcIfaceLetBndr bndrs
676 ; extendIfaceIdEnv ids $ do
677 { rhss' <- mapM tcIfaceExpr rhss
678 ; body' <- tcIfaceExpr body
679 ; return (Let (Rec (ids `zip` rhss')) body') } }
681 (bndrs, rhss) = unzip pairs
683 tcIfaceExpr (IfaceCast expr co) = do
684 expr' <- tcIfaceExpr expr
685 co' <- tcIfaceType co
686 returnM (Cast expr' co')
688 tcIfaceExpr (IfaceNote note expr)
689 = tcIfaceExpr expr `thenM` \ expr' ->
691 IfaceInlineMe -> returnM (Note InlineMe expr')
692 IfaceSCC cc -> returnM (Note (SCC cc) expr')
693 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
695 -------------------------
696 tcIfaceAlt _ (IfaceDefault, names, rhs)
697 = ASSERT( null names )
698 tcIfaceExpr rhs `thenM` \ rhs' ->
699 returnM (DEFAULT, [], rhs')
701 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
702 = ASSERT( null names )
703 tcIfaceExpr rhs `thenM` \ rhs' ->
704 returnM (LitAlt lit, [], rhs')
706 -- A case alternative is made quite a bit more complicated
707 -- by the fact that we omit type annotations because we can
708 -- work them out. True enough, but its not that easy!
709 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
710 = do { con <- tcIfaceDataCon data_occ
711 ; ASSERT2( con `elem` tyConDataCons tycon,
712 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
713 tcIfaceDataAlt con inst_tys arg_strs rhs }
715 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
716 = ASSERT( isTupleTyCon tycon )
717 do { let [data_con] = tyConDataCons tycon
718 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
720 tcIfaceDataAlt con inst_tys arg_strs rhs
721 = do { us <- newUniqueSupply
722 ; let uniqs = uniqsFromSupply us
723 ; let (ex_tvs, co_tvs, arg_ids)
724 = dataConRepFSInstPat arg_strs uniqs con inst_tys
725 all_tvs = ex_tvs ++ co_tvs
727 ; rhs' <- extendIfaceTyVarEnv all_tvs $
728 extendIfaceIdEnv arg_ids $
730 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
735 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
736 tcExtCoreBindings [] = return []
737 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
739 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
740 do_one (IfaceNonRec bndr rhs) thing_inside
741 = do { rhs' <- tcIfaceExpr rhs
742 ; bndr' <- newExtCoreBndr bndr
743 ; extendIfaceIdEnv [bndr'] $ do
744 { core_binds <- thing_inside
745 ; return (NonRec bndr' rhs' : core_binds) }}
747 do_one (IfaceRec pairs) thing_inside
748 = do { bndrs' <- mappM newExtCoreBndr bndrs
749 ; extendIfaceIdEnv bndrs' $ do
750 { rhss' <- mappM tcIfaceExpr rhss
751 ; core_binds <- thing_inside
752 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
754 (bndrs,rhss) = unzip pairs
758 %************************************************************************
762 %************************************************************************
765 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
766 tcIdInfo ignore_prags name ty info
767 | ignore_prags = return vanillaIdInfo
768 | otherwise = case info of
769 NoInfo -> return vanillaIdInfo
770 HasInfo info -> foldlM tcPrag init_info info
772 -- Set the CgInfo to something sensible but uninformative before
773 -- we start; default assumption is that it has CAFs
774 init_info = vanillaIdInfo
776 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
777 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
778 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
780 -- The next two are lazy, so they don't transitively suck stuff in
781 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
782 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
783 tcPrag info (HsUnfold expr)
784 = tcPragExpr name expr `thenM` \ maybe_expr' ->
786 -- maybe_expr' doesn't get looked at if the unfolding
787 -- is never inspected; so the typecheck doesn't even happen
788 unfold_info = case maybe_expr' of
789 Nothing -> noUnfolding
790 Just expr' -> mkTopUnfolding expr'
792 returnM (info `setUnfoldingInfoLazily` unfold_info)
796 tcWorkerInfo ty info wkr arity
797 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
799 -- We return without testing maybe_wkr_id, but as soon as info is
800 -- looked at we will test it. That's ok, because its outside the
801 -- knot; and there seems no big reason to further defer the
802 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
803 -- over the unfolding until it's actually used does seem worth while.)
804 ; us <- newUniqueSupply
806 ; returnM (case mb_wkr_id of
808 Just wkr_id -> add_wkr_info us wkr_id info) }
810 doc = text "Worker for" <+> ppr wkr
811 add_wkr_info us wkr_id info
812 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
813 `setWorkerInfo` HasWorker wkr_id arity
815 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
817 -- We are relying here on strictness info always appearing
818 -- before worker info, fingers crossed ....
819 strict_sig = case newStrictnessInfo info of
821 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
824 For unfoldings we try to do the job lazily, so that we never type check
825 an unfolding that isn't going to be looked at.
828 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
831 tcIfaceExpr expr `thenM` \ core_expr' ->
833 -- Check for type consistency in the unfolding
834 ifOptM Opt_DoCoreLinting (
835 get_in_scope_ids `thenM` \ in_scope ->
836 case lintUnfolding noSrcLoc in_scope core_expr' of
837 Nothing -> returnM ()
838 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
843 doc = text "Unfolding of" <+> ppr name
844 get_in_scope_ids -- Urgh; but just for linting
846 do { env <- getGblEnv
847 ; case if_rec_types env of {
848 Nothing -> return [] ;
849 Just (_, get_env) -> do
850 { type_env <- get_env
851 ; return (typeEnvIds type_env) }}}
856 %************************************************************************
858 Getting from Names to TyThings
860 %************************************************************************
863 tcIfaceGlobal :: Name -> IfL TyThing
865 | Just thing <- wiredInNameTyThing_maybe name
866 -- Wired-in things include TyCons, DataCons, and Ids
867 = do { ifCheckWiredInThing name; return thing }
869 = do { (eps,hpt) <- getEpsAndHpt
871 ; case lookupType dflags hpt (eps_PTE eps) name of {
872 Just thing -> return thing ;
876 ; case if_rec_types env of {
877 Just (mod, get_type_env)
878 | nameIsLocalOrFrom mod name
879 -> do -- It's defined in the module being compiled
880 { type_env <- setLclEnv () get_type_env -- yuk
881 ; case lookupNameEnv type_env name of
882 Just thing -> return thing
883 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
884 (ppr name $$ ppr type_env) }
888 { mb_thing <- importDecl name -- It's imported; go get it
890 Failed err -> failIfM err
891 Succeeded thing -> return thing
894 ifCheckWiredInThing :: Name -> IfL ()
895 -- Even though we are in an interface file, we want to make
896 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
897 -- Ditto want to ensure that RULES are loaded too
898 ifCheckWiredInThing name
899 = do { mod <- getIfModule
900 -- Check whether we are typechecking the interface for this
901 -- very module. E.g when compiling the base library in --make mode
902 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
903 -- the HPT, so without the test we'll demand-load it into the PIT!
904 -- C.f. the same test in checkWiredInTyCon above
905 ; unless (mod == nameModule name)
906 (loadWiredInHomeIface name) }
908 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
909 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
910 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
911 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
912 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
913 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
914 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
915 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
916 ; return (check_tc (tyThingTyCon thing)) }
919 check_tc tc = case toIfaceTyCon tc of
921 other -> pprTrace "check_tc" (ppr tc) tc
925 -- we should be okay just returning Kind constructors without extra loading
926 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
927 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
928 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
929 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
930 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
932 -- Even though we are in an interface file, we want to make
933 -- sure the instances and RULES of this tycon are loaded
934 -- Imagine: f :: Double -> Double
935 tcWiredInTyCon :: TyCon -> IfL TyCon
936 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
939 tcIfaceClass :: Name -> IfL Class
940 tcIfaceClass name = do { thing <- tcIfaceGlobal name
941 ; return (tyThingClass thing) }
943 tcIfaceDataCon :: Name -> IfL DataCon
944 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
946 ADataCon dc -> return dc
947 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
949 tcIfaceExtId :: Name -> IfL Id
950 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
953 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
956 %************************************************************************
960 %************************************************************************
963 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
964 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
965 = do { name <- newIfaceName (mkVarOccFS fs)
966 ; ty' <- tcIfaceType ty
967 ; let id = mkLocalId name ty'
968 ; extendIfaceIdEnv [id] (thing_inside id) }
969 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
970 = bindIfaceTyVar bndr thing_inside
972 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
973 bindIfaceBndrs [] thing_inside = thing_inside []
974 bindIfaceBndrs (b:bs) thing_inside
975 = bindIfaceBndr b $ \ b' ->
976 bindIfaceBndrs bs $ \ bs' ->
977 thing_inside (b':bs')
979 -----------------------
980 tcIfaceLetBndr (IfLetBndr fs ty info)
981 = do { name <- newIfaceName (mkVarOccFS fs)
982 ; ty' <- tcIfaceType ty
984 NoInfo -> return (mkLocalId name ty')
985 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
987 -- Similar to tcIdInfo, but much simpler
988 tc_info [] = vanillaIdInfo
989 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
990 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
991 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
992 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
993 (ppr other) (tc_info i)
995 -----------------------
996 newExtCoreBndr :: IfaceLetBndr -> IfL Id
997 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
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) }