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 :: 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
232 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
235 ; if not (isOneShot mode)
236 -- In --make and interactive mode, if this module has an hs-boot file
237 -- we'll have compiled it already, and it'll be in the HPT
239 -- We check wheher the interface is a *boot* interface.
240 -- It can happen (when using GHC from Visual Studio) that we
241 -- compile a module in TypecheckOnly mode, with a stable,
242 -- fully-populated HPT. In that case the boot interface isn't there
243 -- (it's been replaced by the mother module) so we can't check it.
244 -- And that's fine, because if M's ModInfo is in the HPT, then
245 -- it's been compiled once, and we don't need to check the boot iface
246 then do { hpt <- getHpt
247 ; case lookupUFM hpt (moduleName mod) of
248 Just info | mi_boot (hm_iface info)
249 -> return (hm_details info)
250 other -> return emptyModDetails }
253 -- OK, so we're in one-shot mode.
254 -- In that case, we're read all the direct imports by now,
255 -- so eps_is_boot will record if any of our imports mention us by
256 -- way of hi-boot file
258 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
259 Nothing -> return emptyModDetails ; -- The typical case
261 Just (_, False) -> failWithTc moduleLoop ;
262 -- Someone below us imported us!
263 -- This is a loop with no hi-boot in the way
265 Just (_mod, True) -> -- There's a hi-boot interface below us
267 do { read_result <- findAndReadIface
271 ; case read_result of
272 Failed err -> failWithTc (elaborate err)
273 Succeeded (iface, _path) -> typecheckIface iface
276 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
277 <+> ptext SLIT("to compare against the Real Thing")
279 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
280 <+> ptext SLIT("depends on itself")
282 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
283 quotes (ppr mod) <> colon) 4 err
287 %************************************************************************
289 Type and class declarations
291 %************************************************************************
293 When typechecking a data type decl, we *lazily* (via forkM) typecheck
294 the constructor argument types. This is in the hope that we may never
295 poke on those argument types, and hence may never need to load the
296 interface files for types mentioned in the arg types.
299 data Foo.S = MkS Baz.T
300 Mabye we can get away without even loading the interface for Baz!
302 This is not just a performance thing. Suppose we have
303 data Foo.S = MkS Baz.T
304 data Baz.T = MkT Foo.S
305 (in different interface files, of course).
306 Now, first we load and typecheck Foo.S, and add it to the type envt.
307 If we do explore MkS's argument, we'll load and typecheck Baz.T.
308 If we explore MkT's argument we'll find Foo.S already in the envt.
310 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
311 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
312 which isn't done yet.
314 All very cunning. However, there is a rather subtle gotcha which bit
315 me when developing this stuff. When we typecheck the decl for S, we
316 extend the type envt with S, MkS, and all its implicit Ids. Suppose
317 (a bug, but it happened) that the list of implicit Ids depended in
318 turn on the constructor arg types. Then the following sequence of
320 * we build a thunk <t> for the constructor arg tys
321 * we build a thunk for the extended type environment (depends on <t>)
322 * we write the extended type envt into the global EPS mutvar
324 Now we look something up in the type envt
326 * which reads the global type envt out of the global EPS mutvar
327 * but that depends in turn on <t>
329 It's subtle, because, it'd work fine if we typechecked the constructor args
330 eagerly -- they don't need the extended type envt. They just get the extended
331 type envt by accident, because they look at it later.
333 What this means is that the implicitTyThings MUST NOT DEPEND on any of
338 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
342 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
343 = do { name <- lookupIfaceTop occ_name
344 ; ty <- tcIfaceType iface_type
345 ; info <- tcIdInfo ignore_prags name ty info
346 ; return (AnId (mkVanillaGlobal name ty info)) }
348 tcIfaceDecl ignore_prags
349 (IfaceData {ifName = occ_name,
351 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
354 ifGeneric = want_generic,
355 ifFamInst = mb_family })
356 = do { tc_name <- lookupIfaceTop occ_name
357 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
359 { tycon <- fixM ( \ tycon -> do
360 { stupid_theta <- tcIfaceCtxt ctxt
363 Nothing -> return Nothing
365 do { famTyCon <- tcIfaceTyCon fam
366 ; insttys <- mapM tcIfaceType tys
367 ; return $ Just (famTyCon, insttys)
369 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
370 ; buildAlgTyCon tc_name tyvars stupid_theta
371 cons is_rec want_generic gadt_syn famInst
373 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
374 ; return (ATyCon tycon)
377 tcIfaceDecl ignore_prags
378 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
379 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
380 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
381 { tc_name <- lookupIfaceTop occ_name
382 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
383 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki
384 else SynonymTyCon rhs_tyki
385 ; return (ATyCon (buildSynTyCon tc_name tyvars rhs))
388 tcIfaceDecl ignore_prags
389 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
390 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
391 ifATs = rdr_ats, ifSigs = rdr_sigs,
393 -- ToDo: in hs-boot files we should really treat abstract classes specially,
394 -- as we do abstract tycons
395 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
396 { cls_name <- lookupIfaceTop occ_name
397 ; ctxt <- tcIfaceCtxt rdr_ctxt
398 ; sigs <- mappM tc_sig rdr_sigs
399 ; fds <- mappM tc_fd rdr_fds
400 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
401 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
402 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
403 ; return (AClass cls) }
405 tc_sig (IfaceClassOp occ dm rdr_ty)
406 = do { op_name <- lookupIfaceTop occ
407 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
408 -- Must be done lazily for just the same reason as the
409 -- context of a data decl: the type sig might mention the
410 -- class being defined
411 ; return (op_name, dm, op_ty) }
413 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
415 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
416 ; tvs2' <- mappM tcIfaceTyVar tvs2
417 ; return (tvs1', tvs2') }
419 -- For each AT argument compute the position of the corresponding class
420 -- parameter in the class head. This will later serve as a permutation
421 -- vector when checking the validity of instance declarations.
422 setTyThingPoss (ATyCon tycon) atTyVars =
423 let classTyVars = map fst tv_bndrs
425 . map ((`elemIndex` classTyVars) . fst)
427 -- There will be no Nothing, as we already passed renaming
429 ATyCon (setTyConArgPoss tycon poss)
430 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
432 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
433 = do { name <- lookupIfaceTop rdr_name
434 ; return (ATyCon (mkForeignTyCon name ext_name
437 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
439 IfAbstractTyCon -> return mkAbstractTyConRhs
440 IfOpenDataTyCon -> return mkOpenDataTyConRhs
441 IfOpenNewTyCon -> return mkOpenNewTyConRhs
442 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
443 ; return (mkDataTyConRhs data_cons) }
444 IfNewTyCon con -> do { data_con <- tc_con_decl con
445 ; mkNewTyConRhs tycon_name tycon data_con }
447 tc_con_decl (IfCon { ifConInfix = is_infix,
448 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
449 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
450 ifConArgTys = args, ifConFields = field_lbls,
451 ifConStricts = stricts})
452 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
453 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
454 { name <- lookupIfaceTop occ
455 ; eq_spec <- tcIfaceEqSpec spec
456 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
457 -- At one stage I thought that this context checking *had*
458 -- to be lazy, because of possible mutual recursion between the
459 -- type and the classe:
461 -- class Real a where { toRat :: a -> Ratio Integer }
462 -- data (Real a) => Ratio a = ...
463 -- But now I think that the laziness in checking class ops breaks
464 -- the loop, so no laziness needed
466 -- Read the argument types, but lazily to avoid faulting in
467 -- the component types unless they are really needed
468 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
469 ; lbl_names <- mappM lookupIfaceTop field_lbls
471 ; buildDataCon name is_infix {- Not infix -}
473 univ_tyvars ex_tyvars
477 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
482 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
483 ; ty <- tcIfaceType if_ty
488 %************************************************************************
492 %************************************************************************
495 tcIfaceInst :: IfaceInst -> IfL Instance
496 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
497 ifInstCls = cls, ifInstTys = mb_tcs,
499 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
500 tcIfaceExtId dfun_occ
501 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
502 ; return (mkImportedInstance cls mb_tcs' orph dfun oflag) }
504 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
505 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
506 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
507 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
508 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
509 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
511 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
512 ; return (mkImportedFamInst fam mb_tcs' tycon') }
516 %************************************************************************
520 %************************************************************************
522 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
523 are in the type environment. However, remember that typechecking a Rule may
524 (as a side effect) augment the type envt, and so we may need to iterate the process.
527 tcIfaceRules :: Bool -- True <=> ignore rules
530 tcIfaceRules ignore_prags if_rules
531 | ignore_prags = return []
532 | otherwise = mapM tcIfaceRule if_rules
534 tcIfaceRule :: IfaceRule -> IfL CoreRule
535 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
536 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
538 = do { ~(bndrs', args', rhs') <-
539 -- Typecheck the payload lazily, in the hope it'll never be looked at
540 forkM (ptext SLIT("Rule") <+> ftext name) $
541 bindIfaceBndrs bndrs $ \ bndrs' ->
542 do { args' <- mappM tcIfaceExpr args
543 ; rhs' <- tcIfaceExpr rhs
544 ; return (bndrs', args', rhs') }
545 ; let mb_tcs = map ifTopFreeName args
547 ; let this_module = if_mod lcl
548 ; returnM (Rule { ru_name = name, ru_fn = fn, ru_act = act,
549 ru_bndrs = bndrs', ru_args = args',
550 ru_rhs = rhs', ru_orph = orph,
552 ru_local = nameModule fn == this_module }) }
554 -- This function *must* mirror exactly what Rules.topFreeName does
555 -- We could have stored the ru_rough field in the iface file
556 -- but that would be redundant, I think.
557 -- The only wrinkle is that we must not be deceived by
558 -- type syononyms at the top of a type arg. Since
559 -- we can't tell at this point, we are careful not
560 -- to write them out in coreRuleToIfaceRule
561 ifTopFreeName :: IfaceExpr -> Maybe Name
562 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
563 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
564 ifTopFreeName (IfaceExt n) = Just n
565 ifTopFreeName other = Nothing
569 %************************************************************************
573 %************************************************************************
576 tcIfaceType :: IfaceType -> IfL Type
577 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
578 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
579 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
580 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
581 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
582 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
584 tcIfaceTypes tys = mapM tcIfaceType tys
586 -----------------------------------------
587 tcIfacePredType :: IfacePredType -> IfL PredType
588 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
589 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
590 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
592 -----------------------------------------
593 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
594 tcIfaceCtxt sts = mappM tcIfacePredType sts
598 %************************************************************************
602 %************************************************************************
605 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
606 tcIfaceExpr (IfaceType ty)
607 = tcIfaceType ty `thenM` \ ty' ->
610 tcIfaceExpr (IfaceLcl name)
611 = tcIfaceLclId name `thenM` \ id ->
614 tcIfaceExpr (IfaceExt gbl)
615 = tcIfaceExtId gbl `thenM` \ id ->
618 tcIfaceExpr (IfaceLit lit)
621 tcIfaceExpr (IfaceFCall cc ty)
622 = tcIfaceType ty `thenM` \ ty' ->
623 newUnique `thenM` \ u ->
624 returnM (Var (mkFCallId u cc ty'))
626 tcIfaceExpr (IfaceTuple boxity args)
627 = mappM tcIfaceExpr args `thenM` \ args' ->
629 -- Put the missing type arguments back in
630 con_args = map (Type . exprType) args' ++ args'
632 returnM (mkApps (Var con_id) con_args)
635 con_id = dataConWorkId (tupleCon boxity arity)
638 tcIfaceExpr (IfaceLam bndr body)
639 = bindIfaceBndr bndr $ \ bndr' ->
640 tcIfaceExpr body `thenM` \ body' ->
641 returnM (Lam bndr' body')
643 tcIfaceExpr (IfaceApp fun arg)
644 = tcIfaceExpr fun `thenM` \ fun' ->
645 tcIfaceExpr arg `thenM` \ arg' ->
646 returnM (App fun' arg')
648 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
649 = tcIfaceExpr scrut `thenM` \ scrut' ->
650 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
652 scrut_ty = exprType scrut'
653 case_bndr' = mkLocalId case_bndr_name scrut_ty
654 tc_app = splitTyConApp scrut_ty
655 -- NB: Won't always succeed (polymoprhic case)
656 -- but won't be demanded in those cases
657 -- NB: not tcSplitTyConApp; we are looking at Core here
658 -- look through non-rec newtypes to find the tycon that
659 -- corresponds to the datacon in this case alternative
661 extendIfaceIdEnv [case_bndr'] $
662 mappM (tcIfaceAlt tc_app) alts `thenM` \ alts' ->
663 tcIfaceType ty `thenM` \ ty' ->
664 returnM (Case scrut' case_bndr' ty' alts')
666 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
667 = tcIfaceExpr rhs `thenM` \ rhs' ->
668 bindIfaceId bndr $ \ bndr' ->
669 tcIfaceExpr body `thenM` \ body' ->
670 returnM (Let (NonRec bndr' rhs') body')
672 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
673 = bindIfaceIds bndrs $ \ bndrs' ->
674 mappM tcIfaceExpr rhss `thenM` \ rhss' ->
675 tcIfaceExpr body `thenM` \ body' ->
676 returnM (Let (Rec (bndrs' `zip` rhss')) body')
678 (bndrs, rhss) = unzip pairs
680 tcIfaceExpr (IfaceCast expr co) = do
681 expr' <- tcIfaceExpr expr
682 co' <- tcIfaceType co
683 returnM (Cast expr' co')
685 tcIfaceExpr (IfaceNote note expr)
686 = tcIfaceExpr expr `thenM` \ expr' ->
688 IfaceInlineMe -> returnM (Note InlineMe expr')
689 IfaceSCC cc -> returnM (Note (SCC cc) expr')
690 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
692 -------------------------
693 tcIfaceAlt _ (IfaceDefault, names, rhs)
694 = ASSERT( null names )
695 tcIfaceExpr rhs `thenM` \ rhs' ->
696 returnM (DEFAULT, [], rhs')
698 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
699 = ASSERT( null names )
700 tcIfaceExpr rhs `thenM` \ rhs' ->
701 returnM (LitAlt lit, [], rhs')
703 -- A case alternative is made quite a bit more complicated
704 -- by the fact that we omit type annotations because we can
705 -- work them out. True enough, but its not that easy!
706 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
707 = do { con <- tcIfaceDataCon data_occ
708 ; ASSERT2( con `elem` tyConDataCons tycon,
709 ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
710 tcIfaceDataAlt con inst_tys arg_strs rhs }
712 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
713 = ASSERT( isTupleTyCon tycon )
714 do { let [data_con] = tyConDataCons tycon
715 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
717 tcIfaceDataAlt con inst_tys arg_strs rhs
718 = do { us <- newUniqueSupply
719 ; let uniqs = uniqsFromSupply us
720 ; let (ex_tvs, co_tvs, arg_ids)
721 = dataConRepFSInstPat arg_strs uniqs con inst_tys
722 all_tvs = ex_tvs ++ co_tvs
724 ; rhs' <- extendIfaceTyVarEnv all_tvs $
725 extendIfaceIdEnv arg_ids $
727 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
732 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
733 tcExtCoreBindings [] = return []
734 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
736 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
737 do_one (IfaceNonRec bndr rhs) thing_inside
738 = do { rhs' <- tcIfaceExpr rhs
739 ; bndr' <- newExtCoreBndr bndr
740 ; extendIfaceIdEnv [bndr'] $ do
741 { core_binds <- thing_inside
742 ; return (NonRec bndr' rhs' : core_binds) }}
744 do_one (IfaceRec pairs) thing_inside
745 = do { bndrs' <- mappM newExtCoreBndr bndrs
746 ; extendIfaceIdEnv bndrs' $ do
747 { rhss' <- mappM tcIfaceExpr rhss
748 ; core_binds <- thing_inside
749 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
751 (bndrs,rhss) = unzip pairs
755 %************************************************************************
759 %************************************************************************
762 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
763 tcIdInfo ignore_prags name ty info
764 | ignore_prags = return vanillaIdInfo
765 | otherwise = case info of
766 NoInfo -> return vanillaIdInfo
767 HasInfo info -> foldlM tcPrag init_info info
769 -- Set the CgInfo to something sensible but uninformative before
770 -- we start; default assumption is that it has CAFs
771 init_info = vanillaIdInfo
773 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
774 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
775 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
777 -- The next two are lazy, so they don't transitively suck stuff in
778 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
779 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
780 tcPrag info (HsUnfold expr)
781 = tcPragExpr name expr `thenM` \ maybe_expr' ->
783 -- maybe_expr' doesn't get looked at if the unfolding
784 -- is never inspected; so the typecheck doesn't even happen
785 unfold_info = case maybe_expr' of
786 Nothing -> noUnfolding
787 Just expr' -> mkTopUnfolding expr'
789 returnM (info `setUnfoldingInfoLazily` unfold_info)
793 tcWorkerInfo ty info wkr arity
794 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
796 -- We return without testing maybe_wkr_id, but as soon as info is
797 -- looked at we will test it. That's ok, because its outside the
798 -- knot; and there seems no big reason to further defer the
799 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
800 -- over the unfolding until it's actually used does seem worth while.)
801 ; us <- newUniqueSupply
803 ; returnM (case mb_wkr_id of
805 Just wkr_id -> add_wkr_info us wkr_id info) }
807 doc = text "Worker for" <+> ppr wkr
808 add_wkr_info us wkr_id info
809 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
810 `setWorkerInfo` HasWorker wkr_id arity
812 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
814 -- We are relying here on strictness info always appearing
815 -- before worker info, fingers crossed ....
816 strict_sig = case newStrictnessInfo info of
818 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
821 For unfoldings we try to do the job lazily, so that we never type check
822 an unfolding that isn't going to be looked at.
825 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
828 tcIfaceExpr expr `thenM` \ core_expr' ->
830 -- Check for type consistency in the unfolding
831 ifOptM Opt_DoCoreLinting (
832 get_in_scope_ids `thenM` \ in_scope ->
833 case lintUnfolding noSrcLoc in_scope core_expr' of
834 Nothing -> returnM ()
835 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
840 doc = text "Unfolding of" <+> ppr name
841 get_in_scope_ids -- Urgh; but just for linting
843 do { env <- getGblEnv
844 ; case if_rec_types env of {
845 Nothing -> return [] ;
846 Just (_, get_env) -> do
847 { type_env <- get_env
848 ; return (typeEnvIds type_env) }}}
853 %************************************************************************
855 Getting from Names to TyThings
857 %************************************************************************
860 tcIfaceGlobal :: Name -> IfL TyThing
862 | Just thing <- wiredInNameTyThing_maybe name
863 -- Wired-in things include TyCons, DataCons, and Ids
864 = do { ifCheckWiredInThing name; return thing }
866 = do { (eps,hpt) <- getEpsAndHpt
868 ; case lookupType dflags hpt (eps_PTE eps) name of {
869 Just thing -> return thing ;
873 ; case if_rec_types env of {
874 Just (mod, get_type_env)
875 | nameIsLocalOrFrom mod name
876 -> do -- It's defined in the module being compiled
877 { type_env <- setLclEnv () get_type_env -- yuk
878 ; case lookupNameEnv type_env name of
879 Just thing -> return thing
880 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
881 (ppr name $$ ppr type_env) }
885 { mb_thing <- importDecl name -- It's imported; go get it
887 Failed err -> failIfM err
888 Succeeded thing -> return thing
891 ifCheckWiredInThing :: Name -> IfL ()
892 -- Even though we are in an interface file, we want to make
893 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
894 -- Ditto want to ensure that RULES are loaded too
895 ifCheckWiredInThing name
896 = do { mod <- getIfModule
897 -- Check whether we are typechecking the interface for this
898 -- very module. E.g when compiling the base library in --make mode
899 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
900 -- the HPT, so without the test we'll demand-load it into the PIT!
901 -- C.f. the same test in checkWiredInTyCon above
902 ; unless (mod == nameModule name)
903 (loadWiredInHomeIface name) }
905 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
906 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
907 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
908 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
909 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
910 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
911 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
912 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
913 ; return (check_tc (tyThingTyCon thing)) }
916 check_tc tc = case toIfaceTyCon tc of
918 other -> pprTrace "check_tc" (ppr tc) tc
922 -- we should be okay just returning Kind constructors without extra loading
923 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
924 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
925 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
926 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
927 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
929 -- Even though we are in an interface file, we want to make
930 -- sure the instances and RULES of this tycon are loaded
931 -- Imagine: f :: Double -> Double
932 tcWiredInTyCon :: TyCon -> IfL TyCon
933 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
936 tcIfaceClass :: Name -> IfL Class
937 tcIfaceClass name = do { thing <- tcIfaceGlobal name
938 ; return (tyThingClass thing) }
940 tcIfaceDataCon :: Name -> IfL DataCon
941 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
943 ADataCon dc -> return dc
944 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
946 tcIfaceExtId :: Name -> IfL Id
947 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
950 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
953 %************************************************************************
957 %************************************************************************
960 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
961 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
962 = bindIfaceId bndr thing_inside
963 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
964 = bindIfaceTyVar bndr thing_inside
966 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
967 bindIfaceBndrs [] thing_inside = thing_inside []
968 bindIfaceBndrs (b:bs) thing_inside
969 = bindIfaceBndr b $ \ b' ->
970 bindIfaceBndrs bs $ \ bs' ->
971 thing_inside (b':bs')
973 -----------------------
974 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
975 bindIfaceId (occ, ty) thing_inside
976 = do { name <- newIfaceName (mkVarOccFS occ)
977 ; ty' <- tcIfaceType ty
978 ; let { id = mkLocalId name ty' }
979 ; extendIfaceIdEnv [id] (thing_inside id) }
981 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
982 bindIfaceIds bndrs thing_inside
983 = do { names <- newIfaceNames (map mkVarOccFS occs)
984 ; tys' <- mappM tcIfaceType tys
985 ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
986 ; extendIfaceIdEnv ids (thing_inside ids) }
988 (occs,tys) = unzip bndrs
991 -----------------------
992 newExtCoreBndr :: IfaceIdBndr -> IfL Id
993 newExtCoreBndr (var, ty)
994 = do { mod <- getIfModule
995 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcLoc
996 ; ty' <- tcIfaceType ty
997 ; return (mkLocalId name ty') }
999 -----------------------
1000 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1001 bindIfaceTyVar (occ,kind) thing_inside
1002 = do { name <- newIfaceName (mkTyVarOcc occ)
1003 ; tyvar <- mk_iface_tyvar name kind
1004 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1006 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1007 bindIfaceTyVars bndrs thing_inside
1008 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1009 ; tyvars <- TcRnMonad.zipWithM mk_iface_tyvar names kinds
1010 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1012 (occs,kinds) = unzip bndrs
1014 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1015 mk_iface_tyvar name ifKind
1016 = do { kind <- tcIfaceType ifKind
1017 ; if isCoercionKind kind then
1018 return (Var.mkCoVar name kind)
1020 return (Var.mkTyVar name kind) }