2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Type checking of type signatures in interface files
10 tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
11 tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
12 tcIfaceVectInfo, tcIfaceGlobal, tcExtCoreBindings
15 #include "HsVersions.h"
55 import BasicTypes (Arity)
68 An IfaceDecl is populated with RdrNames, and these are not renamed to
69 Names before typechecking, because there should be no scope errors etc.
71 -- For (b) consider: f = $(...h....)
72 -- where h is imported, and calls f via an hi-boot file.
73 -- This is bad! But it is not seen as a staging error, because h
74 -- is indeed imported. We don't want the type-checker to black-hole
75 -- when simplifying and compiling the splice!
77 -- Simple solution: discard any unfolding that mentions a variable
78 -- bound in this module (and hence not yet processed).
79 -- The discarding happens when forkM finds a type error.
81 %************************************************************************
83 %* tcImportDecl is the key function for "faulting in" *
86 %************************************************************************
88 The main idea is this. We are chugging along type-checking source code, and
89 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
90 it in the EPS type envt. So it
92 2 gets the decl for GHC.Base.map
93 3 typechecks it via tcIfaceDecl
94 4 and adds it to the type env in the EPS
96 Note that DURING STEP 4, we may find that map's type mentions a type
99 Notice that for imported things we read the current version from the EPS
100 mutable variable. This is important in situations like
102 where the code that e1 expands to might import some defns that
103 also turn out to be needed by the code that e2 expands to.
106 tcImportDecl :: Name -> TcM TyThing
107 -- Entry point for *source-code* uses of importDecl
109 | Just thing <- wiredInNameTyThing_maybe name
110 = do { initIfaceTcRn (loadWiredInHomeIface name)
111 -- See Note [Loading instances] in LoadIface
114 = do { traceIf (text "tcImportDecl" <+> ppr name)
115 ; mb_thing <- initIfaceTcRn (importDecl name)
117 Succeeded thing -> return thing
118 Failed err -> failWithTc err }
120 checkWiredInTyCon :: TyCon -> TcM ()
121 -- Ensure that the home module of the TyCon (and hence its instances)
122 -- are loaded. See See Note [Loading instances] in LoadIface
123 -- It might not be a wired-in tycon (see the calls in TcUnify),
124 -- in which case this is a no-op.
126 | not (isWiredInName tc_name)
129 = do { mod <- getModule
130 ; unless (mod == nameModule tc_name)
131 (initIfaceTcRn (loadWiredInHomeIface tc_name))
132 -- Don't look for (non-existent) Float.hi when
133 -- compiling Float.lhs, which mentions Float of course
134 -- A bit yukky to call initIfaceTcRn here
137 tc_name = tyConName tc
139 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
140 -- Get the TyThing for this Name from an interface file
141 -- It's not a wired-in thing -- the caller caught that
143 = ASSERT( not (isWiredInName name) )
146 -- Load the interface, which should populate the PTE
147 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
149 Failed err_msg -> return (Failed err_msg) ;
152 -- Now look it up again; this time we should find it
154 ; case lookupTypeEnv (eps_PTE eps) name of
155 Just thing -> return (Succeeded thing)
156 Nothing -> return (Failed not_found_msg)
159 nd_doc = ptext (sLit "Need decl for") <+> ppr name
160 not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
161 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
162 2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
163 ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
166 %************************************************************************
168 Type-checking a complete interface
170 %************************************************************************
172 Suppose we discover we don't need to recompile. Then we must type
173 check the old interface file. This is a bit different to the
174 incremental type checking we do as we suck in interface files. Instead
175 we do things similarly as when we are typechecking source decls: we
176 bring into scope the type envt for the interface all at once, using a
177 knot. Remember, the decls aren't necessarily in dependency order --
178 and even if they were, the type decls might be mutually recursive.
181 typecheckIface :: ModIface -- Get the decls from here
182 -> TcRnIf gbl lcl ModDetails
184 = initIfaceTc iface $ \ tc_env_var -> do
185 -- The tc_env_var is freshly allocated, private to
186 -- type-checking this particular interface
187 { -- Get the right set of decls and rules. If we are compiling without -O
188 -- we discard pragmas before typechecking, so that we don't "see"
189 -- information that we shouldn't. From a versioning point of view
190 -- It's not actually *wrong* to do so, but in fact GHCi is unable
191 -- to handle unboxed tuples, so it must not see unfoldings.
192 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
194 -- Typecheck the decls. This is done lazily, so that the knot-tying
195 -- within this single module work out right. In the If monad there is
196 -- no global envt for the current interface; instead, the knot is tied
197 -- through the if_rec_types field of IfGblEnv
198 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
199 ; let type_env = mkNameEnv names_w_things
200 ; writeMutVar tc_env_var type_env
202 -- Now do those rules and instances
203 ; insts <- mapM tcIfaceInst (mi_insts iface)
204 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
205 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
207 -- Vectorisation information
208 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
212 ; exports <- ifaceExportNames (mi_exports iface)
215 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
216 text "Type envt:" <+> ppr type_env])
217 ; return $ ModDetails { md_types = type_env
219 , md_fam_insts = fam_insts
221 , md_vect_info = vect_info
222 , md_exports = exports
228 %************************************************************************
230 Type and class declarations
232 %************************************************************************
235 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
236 -- Load the hi-boot iface for the module being compiled,
237 -- if it indeed exists in the transitive closure of imports
238 -- Return the ModDetails, empty if no hi-boot iface
239 tcHiBootIface hsc_src mod
240 | isHsBoot hsc_src -- Already compiling a hs-boot file
241 = return emptyModDetails
243 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
246 ; if not (isOneShot mode)
247 -- In --make and interactive mode, if this module has an hs-boot file
248 -- we'll have compiled it already, and it'll be in the HPT
250 -- We check wheher the interface is a *boot* interface.
251 -- It can happen (when using GHC from Visual Studio) that we
252 -- compile a module in TypecheckOnly mode, with a stable,
253 -- fully-populated HPT. In that case the boot interface isn't there
254 -- (it's been replaced by the mother module) so we can't check it.
255 -- And that's fine, because if M's ModInfo is in the HPT, then
256 -- it's been compiled once, and we don't need to check the boot iface
257 then do { hpt <- getHpt
258 ; case lookupUFM hpt (moduleName mod) of
259 Just info | mi_boot (hm_iface info)
260 -> return (hm_details info)
261 _ -> return emptyModDetails }
264 -- OK, so we're in one-shot mode.
265 -- In that case, we're read all the direct imports by now,
266 -- so eps_is_boot will record if any of our imports mention us by
267 -- way of hi-boot file
269 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
270 Nothing -> return emptyModDetails ; -- The typical case
272 Just (_, False) -> failWithTc moduleLoop ;
273 -- Someone below us imported us!
274 -- This is a loop with no hi-boot in the way
276 Just (_mod, True) -> -- There's a hi-boot interface below us
278 do { read_result <- findAndReadIface
282 ; case read_result of
283 Failed err -> failWithTc (elaborate err)
284 Succeeded (iface, _path) -> typecheckIface iface
287 need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
288 <+> ptext (sLit "to compare against the Real Thing")
290 moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod)
291 <+> ptext (sLit "depends on itself")
293 elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+>
294 quotes (ppr mod) <> colon) 4 err
298 %************************************************************************
300 Type and class declarations
302 %************************************************************************
304 When typechecking a data type decl, we *lazily* (via forkM) typecheck
305 the constructor argument types. This is in the hope that we may never
306 poke on those argument types, and hence may never need to load the
307 interface files for types mentioned in the arg types.
310 data Foo.S = MkS Baz.T
311 Mabye we can get away without even loading the interface for Baz!
313 This is not just a performance thing. Suppose we have
314 data Foo.S = MkS Baz.T
315 data Baz.T = MkT Foo.S
316 (in different interface files, of course).
317 Now, first we load and typecheck Foo.S, and add it to the type envt.
318 If we do explore MkS's argument, we'll load and typecheck Baz.T.
319 If we explore MkT's argument we'll find Foo.S already in the envt.
321 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
322 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
323 which isn't done yet.
325 All very cunning. However, there is a rather subtle gotcha which bit
326 me when developing this stuff. When we typecheck the decl for S, we
327 extend the type envt with S, MkS, and all its implicit Ids. Suppose
328 (a bug, but it happened) that the list of implicit Ids depended in
329 turn on the constructor arg types. Then the following sequence of
331 * we build a thunk <t> for the constructor arg tys
332 * we build a thunk for the extended type environment (depends on <t>)
333 * we write the extended type envt into the global EPS mutvar
335 Now we look something up in the type envt
337 * which reads the global type envt out of the global EPS mutvar
338 * but that depends in turn on <t>
340 It's subtle, because, it'd work fine if we typechecked the constructor args
341 eagerly -- they don't need the extended type envt. They just get the extended
342 type envt by accident, because they look at it later.
344 What this means is that the implicitTyThings MUST NOT DEPEND on any of
349 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
353 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
354 = do { name <- lookupIfaceTop occ_name
355 ; ty <- tcIfaceType iface_type
356 ; info <- tcIdInfo ignore_prags name ty info
357 ; return (AnId (mkVanillaGlobal name ty info)) }
360 (IfaceData {ifName = occ_name,
362 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
365 ifGeneric = want_generic,
366 ifFamInst = mb_family })
367 = do { tc_name <- lookupIfaceTop occ_name
368 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
370 { tycon <- fixM ( \ tycon -> do
371 { stupid_theta <- tcIfaceCtxt ctxt
374 Nothing -> return Nothing
376 do { famTyCon <- tcIfaceTyCon fam
377 ; insttys <- mapM tcIfaceType tys
378 ; return $ Just (famTyCon, insttys)
380 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
381 ; buildAlgTyCon tc_name tyvars stupid_theta
382 cons is_rec want_generic gadt_syn famInst
384 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
385 ; return (ATyCon tycon)
389 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
390 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty,
391 ifFamInst = mb_family})
392 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
393 { tc_name <- lookupIfaceTop occ_name
394 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
395 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
396 else SynonymTyCon rhs_tyki
397 ; famInst <- case mb_family of
398 Nothing -> return Nothing
400 do { famTyCon <- tcIfaceTyCon fam
401 ; insttys <- mapM tcIfaceType tys
402 ; return $ Just (famTyCon, insttys)
404 ; tycon <- buildSynTyCon tc_name tyvars rhs famInst
405 ; return $ ATyCon tycon
408 tcIfaceDecl ignore_prags
409 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
410 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
411 ifATs = rdr_ats, ifSigs = rdr_sigs,
413 -- ToDo: in hs-boot files we should really treat abstract classes specially,
414 -- as we do abstract tycons
415 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
416 { cls_name <- lookupIfaceTop occ_name
417 ; ctxt <- tcIfaceCtxt rdr_ctxt
418 ; sigs <- mapM tc_sig rdr_sigs
419 ; fds <- mapM tc_fd rdr_fds
420 ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
421 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
422 ; cls <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
423 ; return (AClass cls) }
425 tc_sig (IfaceClassOp occ dm rdr_ty)
426 = do { op_name <- lookupIfaceTop occ
427 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
428 -- Must be done lazily for just the same reason as the
429 -- type of a data con; to avoid sucking in types that
430 -- it mentions unless it's necessray to do so
431 ; return (op_name, dm, op_ty) }
433 mk_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
435 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
436 ; tvs2' <- mapM tcIfaceTyVar tvs2
437 ; return (tvs1', tvs2') }
439 -- For each AT argument compute the position of the corresponding class
440 -- parameter in the class head. This will later serve as a permutation
441 -- vector when checking the validity of instance declarations.
442 setTyThingPoss (ATyCon tycon) atTyVars =
443 let classTyVars = map fst tv_bndrs
445 . map ((`elemIndex` classTyVars) . fst)
447 -- There will be no Nothing, as we already passed renaming
449 ATyCon (setTyConArgPoss tycon poss)
450 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
452 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
453 = do { name <- lookupIfaceTop rdr_name
454 ; return (ATyCon (mkForeignTyCon name ext_name
457 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
458 tcIfaceDataCons tycon_name tycon _ if_cons
460 IfAbstractTyCon -> return mkAbstractTyConRhs
461 IfOpenDataTyCon -> return mkOpenDataTyConRhs
462 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
463 ; return (mkDataTyConRhs data_cons) }
464 IfNewTyCon con -> do { data_con <- tc_con_decl con
465 ; mkNewTyConRhs tycon_name tycon data_con }
467 tc_con_decl (IfCon { ifConInfix = is_infix,
468 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
469 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
470 ifConArgTys = args, ifConFields = field_lbls,
471 ifConStricts = stricts})
472 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
473 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
474 { name <- lookupIfaceTop occ
475 ; eq_spec <- tcIfaceEqSpec spec
476 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
477 -- At one stage I thought that this context checking *had*
478 -- to be lazy, because of possible mutual recursion between the
479 -- type and the classe:
481 -- class Real a where { toRat :: a -> Ratio Integer }
482 -- data (Real a) => Ratio a = ...
483 -- But now I think that the laziness in checking class ops breaks
484 -- the loop, so no laziness needed
486 -- Read the argument types, but lazily to avoid faulting in
487 -- the component types unless they are really needed
488 ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
489 ; lbl_names <- mapM lookupIfaceTop field_lbls
491 ; buildDataCon name is_infix {- Not infix -}
493 univ_tyvars ex_tyvars
497 mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
499 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
503 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
504 ; ty <- tcIfaceType if_ty
509 %************************************************************************
513 %************************************************************************
516 tcIfaceInst :: IfaceInst -> IfL Instance
517 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
518 ifInstCls = cls, ifInstTys = mb_tcs })
519 = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
520 tcIfaceExtId dfun_occ
521 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
522 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
524 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
525 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
526 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
527 -- { tycon' <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
528 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
529 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
531 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
532 return (mkImportedFamInst fam mb_tcs' tycon')
536 %************************************************************************
540 %************************************************************************
542 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
543 are in the type environment. However, remember that typechecking a Rule may
544 (as a side effect) augment the type envt, and so we may need to iterate the process.
547 tcIfaceRules :: Bool -- True <=> ignore rules
550 tcIfaceRules ignore_prags if_rules
551 | ignore_prags = return []
552 | otherwise = mapM tcIfaceRule if_rules
554 tcIfaceRule :: IfaceRule -> IfL CoreRule
555 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
556 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
557 = do { ~(bndrs', args', rhs') <-
558 -- Typecheck the payload lazily, in the hope it'll never be looked at
559 forkM (ptext (sLit "Rule") <+> ftext name) $
560 bindIfaceBndrs bndrs $ \ bndrs' ->
561 do { args' <- mapM tcIfaceExpr args
562 ; rhs' <- tcIfaceExpr rhs
563 ; return (bndrs', args', rhs') }
564 ; let mb_tcs = map ifTopFreeName args
565 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
566 ru_bndrs = bndrs', ru_args = args',
569 ru_local = False }) } -- An imported RULE is never for a local Id
570 -- or, even if it is (module loop, perhaps)
571 -- we'll just leave it in the non-local set
573 -- This function *must* mirror exactly what Rules.topFreeName does
574 -- We could have stored the ru_rough field in the iface file
575 -- but that would be redundant, I think.
576 -- The only wrinkle is that we must not be deceived by
577 -- type syononyms at the top of a type arg. Since
578 -- we can't tell at this point, we are careful not
579 -- to write them out in coreRuleToIfaceRule
580 ifTopFreeName :: IfaceExpr -> Maybe Name
581 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
582 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
583 ifTopFreeName (IfaceExt n) = Just n
584 ifTopFreeName _ = Nothing
588 %************************************************************************
590 Vectorisation information
592 %************************************************************************
595 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
596 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
597 { ifaceVectInfoVar = vars
598 , ifaceVectInfoTyCon = tycons
599 , ifaceVectInfoTyConReuse = tyconsReuse
601 = do { vVars <- mapM vectVarMapping vars
602 ; tyConRes1 <- mapM vectTyConMapping tycons
603 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
604 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
606 { vectInfoVar = mkVarEnv vVars
607 , vectInfoTyCon = mkNameEnv vTyCons
608 , vectInfoDataCon = mkNameEnv (concat vDataCons)
609 , vectInfoPADFun = mkNameEnv vPAs
610 , vectInfoIso = mkNameEnv vIsos
615 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
616 ; let { var = lookupVar name
617 ; vVar = lookupVar vName
619 ; return (var, (var, vVar))
621 vectTyConMapping name
622 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
623 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
624 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
625 ; let { tycon = lookupTyCon name
626 ; vTycon = lookupTyCon vName
627 ; paTycon = lookupVar paName
628 ; isoTycon = lookupVar isoName
630 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
631 ; return ((name, (tycon, vTycon)), -- (T, T_v)
632 vDataCons, -- list of (Ci, Ci_v)
633 (vName, (vTycon, paTycon)), -- (T_v, paT)
634 (name, (tycon, isoTycon))) -- (T, isoT)
636 vectTyConReuseMapping name
637 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
638 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
639 ; let { tycon = lookupTyCon name
640 ; paTycon = lookupVar paName
641 ; isoTycon = lookupVar isoName
642 ; vDataCons = [ (dataConName dc, (dc, dc))
643 | dc <- tyConDataCons tycon]
645 ; return ((name, (tycon, tycon)), -- (T, T)
646 vDataCons, -- list of (Ci, Ci)
647 (name, (tycon, paTycon)), -- (T, paT)
648 (name, (tycon, isoTycon))) -- (T, isoT)
650 vectDataConMapping datacon
651 = do { let name = dataConName datacon
652 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
653 ; let vDataCon = lookupDataCon vName
654 ; return (name, (datacon, vDataCon))
657 lookupVar name = case lookupTypeEnv typeEnv name of
658 Just (AnId var) -> var
660 panic "TcIface.tcIfaceVectInfo: not an id"
662 panic "TcIface.tcIfaceVectInfo: unknown name"
663 lookupTyCon name = case lookupTypeEnv typeEnv name of
664 Just (ATyCon tc) -> tc
666 panic "TcIface.tcIfaceVectInfo: not a tycon"
668 panic "TcIface.tcIfaceVectInfo: unknown name"
669 lookupDataCon name = case lookupTypeEnv typeEnv name of
670 Just (ADataCon dc) -> dc
672 panic "TcIface.tcIfaceVectInfo: not a datacon"
674 panic "TcIface.tcIfaceVectInfo: unknown name"
677 %************************************************************************
681 %************************************************************************
684 tcIfaceType :: IfaceType -> IfL Type
685 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
686 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
687 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
688 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
689 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
690 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
692 tcIfaceTypes :: [IfaceType] -> IfL [Type]
693 tcIfaceTypes tys = mapM tcIfaceType tys
695 -----------------------------------------
696 tcIfacePredType :: IfacePredType -> IfL PredType
697 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
698 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
699 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
701 -----------------------------------------
702 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
703 tcIfaceCtxt sts = mapM tcIfacePredType sts
707 %************************************************************************
711 %************************************************************************
714 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
715 tcIfaceExpr (IfaceType ty)
716 = Type <$> tcIfaceType ty
718 tcIfaceExpr (IfaceLcl name)
719 = Var <$> tcIfaceLclId name
721 tcIfaceExpr (IfaceTick modName tickNo)
722 = Var <$> tcIfaceTick modName tickNo
724 tcIfaceExpr (IfaceExt gbl)
725 = Var <$> tcIfaceExtId gbl
727 tcIfaceExpr (IfaceLit lit)
730 tcIfaceExpr (IfaceFCall cc ty) = do
731 ty' <- tcIfaceType ty
733 return (Var (mkFCallId u cc ty'))
735 tcIfaceExpr (IfaceTuple boxity args) = do
736 args' <- mapM tcIfaceExpr args
737 -- Put the missing type arguments back in
738 let con_args = map (Type . exprType) args' ++ args'
739 return (mkApps (Var con_id) con_args)
742 con_id = dataConWorkId (tupleCon boxity arity)
745 tcIfaceExpr (IfaceLam bndr body)
746 = bindIfaceBndr bndr $ \bndr' ->
747 Lam bndr' <$> tcIfaceExpr body
749 tcIfaceExpr (IfaceApp fun arg)
750 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
752 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
753 scrut' <- tcIfaceExpr scrut
754 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
756 scrut_ty = exprType scrut'
757 case_bndr' = mkLocalId case_bndr_name scrut_ty
758 tc_app = splitTyConApp scrut_ty
759 -- NB: Won't always succeed (polymoprhic case)
760 -- but won't be demanded in those cases
761 -- NB: not tcSplitTyConApp; we are looking at Core here
762 -- look through non-rec newtypes to find the tycon that
763 -- corresponds to the datacon in this case alternative
765 extendIfaceIdEnv [case_bndr'] $ do
766 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
767 ty' <- tcIfaceType ty
768 return (Case scrut' case_bndr' ty' alts')
770 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
771 rhs' <- tcIfaceExpr rhs
772 id <- tcIfaceLetBndr bndr
773 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
774 return (Let (NonRec id rhs') body')
776 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
777 ids <- mapM tcIfaceLetBndr bndrs
778 extendIfaceIdEnv ids $ do
779 rhss' <- mapM tcIfaceExpr rhss
780 body' <- tcIfaceExpr body
781 return (Let (Rec (ids `zip` rhss')) body')
783 (bndrs, rhss) = unzip pairs
785 tcIfaceExpr (IfaceCast expr co) = do
786 expr' <- tcIfaceExpr expr
787 co' <- tcIfaceType co
788 return (Cast expr' co')
790 tcIfaceExpr (IfaceNote note expr) = do
791 expr' <- tcIfaceExpr expr
793 IfaceInlineMe -> return (Note InlineMe expr')
794 IfaceSCC cc -> return (Note (SCC cc) expr')
795 IfaceCoreNote n -> return (Note (CoreNote n) expr')
797 -------------------------
798 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
799 -> (IfaceConAlt, [FastString], IfaceExpr)
800 -> IfL (AltCon, [TyVar], CoreExpr)
801 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
802 = ASSERT( null names ) do
803 rhs' <- tcIfaceExpr rhs
804 return (DEFAULT, [], rhs')
806 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
807 = ASSERT( null names ) do
808 rhs' <- tcIfaceExpr rhs
809 return (LitAlt lit, [], rhs')
811 -- A case alternative is made quite a bit more complicated
812 -- by the fact that we omit type annotations because we can
813 -- work them out. True enough, but its not that easy!
814 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
815 = do { con <- tcIfaceDataCon data_occ
816 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
817 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
818 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
820 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
821 = ASSERT( isTupleTyCon tycon )
822 do { let [data_con] = tyConDataCons tycon
823 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
825 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
826 -> IfL (AltCon, [TyVar], CoreExpr)
827 tcIfaceDataAlt con inst_tys arg_strs rhs
828 = do { us <- newUniqueSupply
829 ; let uniqs = uniqsFromSupply us
830 ; let (ex_tvs, co_tvs, arg_ids)
831 = dataConRepFSInstPat arg_strs uniqs con inst_tys
832 all_tvs = ex_tvs ++ co_tvs
834 ; rhs' <- extendIfaceTyVarEnv all_tvs $
835 extendIfaceIdEnv arg_ids $
837 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
842 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
843 tcExtCoreBindings [] = return []
844 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
846 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
847 do_one (IfaceNonRec bndr rhs) thing_inside
848 = do { rhs' <- tcIfaceExpr rhs
849 ; bndr' <- newExtCoreBndr bndr
850 ; extendIfaceIdEnv [bndr'] $ do
851 { core_binds <- thing_inside
852 ; return (NonRec bndr' rhs' : core_binds) }}
854 do_one (IfaceRec pairs) thing_inside
855 = do { bndrs' <- mapM newExtCoreBndr bndrs
856 ; extendIfaceIdEnv bndrs' $ do
857 { rhss' <- mapM tcIfaceExpr rhss
858 ; core_binds <- thing_inside
859 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
861 (bndrs,rhss) = unzip pairs
865 %************************************************************************
869 %************************************************************************
872 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
873 tcIdInfo ignore_prags name ty info
874 | ignore_prags = return vanillaIdInfo
875 | otherwise = case info of
876 NoInfo -> return vanillaIdInfo
877 HasInfo info -> foldlM tcPrag init_info info
879 -- Set the CgInfo to something sensible but uninformative before
880 -- we start; default assumption is that it has CAFs
881 init_info = vanillaIdInfo
883 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
884 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
885 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
887 -- The next two are lazy, so they don't transitively suck stuff in
888 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
889 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
890 tcPrag info (HsUnfold expr) = do
891 maybe_expr' <- tcPragExpr name expr
893 -- maybe_expr' doesn't get looked at if the unfolding
894 -- is never inspected; so the typecheck doesn't even happen
895 unfold_info = case maybe_expr' of
896 Nothing -> noUnfolding
897 Just expr' -> mkTopUnfolding expr'
898 return (info `setUnfoldingInfoLazily` unfold_info)
902 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
903 tcWorkerInfo ty info wkr arity
904 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
906 -- We return without testing maybe_wkr_id, but as soon as info is
907 -- looked at we will test it. That's ok, because its outside the
908 -- knot; and there seems no big reason to further defer the
909 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
910 -- over the unfolding until it's actually used does seem worth while.)
911 ; us <- newUniqueSupply
913 ; return (case mb_wkr_id of
915 Just wkr_id -> add_wkr_info us wkr_id info) }
917 doc = text "Worker for" <+> ppr wkr
918 add_wkr_info us wkr_id info
919 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
920 `setWorkerInfo` HasWorker wkr_id arity
922 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
924 -- We are relying here on strictness info always appearing
925 -- before worker info, fingers crossed ....
926 strict_sig = case newStrictnessInfo info of
928 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
931 For unfoldings we try to do the job lazily, so that we never type check
932 an unfolding that isn't going to be looked at.
935 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
937 = forkM_maybe doc $ do
938 core_expr' <- tcIfaceExpr expr
940 -- Check for type consistency in the unfolding
941 ifOptM Opt_DoCoreLinting $ do
942 in_scope <- get_in_scope_ids
943 case lintUnfolding noSrcLoc in_scope core_expr' of
945 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
949 doc = text "Unfolding of" <+> ppr name
950 get_in_scope_ids -- Urgh; but just for linting
952 do { env <- getGblEnv
953 ; case if_rec_types env of {
954 Nothing -> return [] ;
955 Just (_, get_env) -> do
956 { type_env <- get_env
957 ; return (typeEnvIds type_env) }}}
962 %************************************************************************
964 Getting from Names to TyThings
966 %************************************************************************
969 tcIfaceGlobal :: Name -> IfL TyThing
971 | Just thing <- wiredInNameTyThing_maybe name
972 -- Wired-in things include TyCons, DataCons, and Ids
973 = do { ifCheckWiredInThing name; return thing }
975 = do { env <- getGblEnv
976 ; case if_rec_types env of { -- Note [Tying the knot]
977 Just (mod, get_type_env)
978 | nameIsLocalOrFrom mod name
979 -> do -- It's defined in the module being compiled
980 { type_env <- setLclEnv () get_type_env -- yuk
981 ; case lookupNameEnv type_env name of
982 Just thing -> return thing
983 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
984 (ppr name $$ ppr type_env) }
988 { (eps,hpt) <- getEpsAndHpt
990 ; case lookupType dflags hpt (eps_PTE eps) name of {
991 Just thing -> return thing ;
994 { mb_thing <- importDecl name -- It's imported; go get it
996 Failed err -> failIfM err
997 Succeeded thing -> return thing
1000 -- Note [Tying the knot]
1001 -- ~~~~~~~~~~~~~~~~~~~~~
1002 -- The if_rec_types field is used in two situations:
1004 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1005 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1006 -- after we've built M's type envt.
1008 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1009 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1010 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1012 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1013 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1014 -- emasculated form (e.g. lacking data constructors).
1016 ifCheckWiredInThing :: Name -> IfL ()
1017 -- Even though we are in an interface file, we want to make
1018 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1019 -- Ditto want to ensure that RULES are loaded too
1020 -- See Note [Loading instances] in LoadIface
1021 ifCheckWiredInThing name
1022 = do { mod <- getIfModule
1023 -- Check whether we are typechecking the interface for this
1024 -- very module. E.g when compiling the base library in --make mode
1025 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1026 -- the HPT, so without the test we'll demand-load it into the PIT!
1027 -- C.f. the same test in checkWiredInTyCon above
1028 ; unless (mod == nameModule name)
1029 (loadWiredInHomeIface name) }
1031 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1032 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1033 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1034 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1035 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1036 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1037 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1038 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1039 ; return (check_tc (tyThingTyCon thing)) }
1042 | debugIsOn = case toIfaceTyCon tc of
1044 _ -> pprTrace "check_tc" (ppr tc) tc
1046 -- we should be okay just returning Kind constructors without extra loading
1047 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1048 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1049 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1050 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1051 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1053 -- Even though we are in an interface file, we want to make
1054 -- sure the instances and RULES of this tycon are loaded
1055 -- Imagine: f :: Double -> Double
1056 tcWiredInTyCon :: TyCon -> IfL TyCon
1057 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1060 tcIfaceClass :: Name -> IfL Class
1061 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1062 ; return (tyThingClass thing) }
1064 tcIfaceDataCon :: Name -> IfL DataCon
1065 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1067 ADataCon dc -> return dc
1068 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1070 tcIfaceExtId :: Name -> IfL Id
1071 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1073 AnId id -> return id
1074 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1077 %************************************************************************
1081 %************************************************************************
1084 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1085 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1086 = do { name <- newIfaceName (mkVarOccFS fs)
1087 ; ty' <- tcIfaceType ty
1088 ; let id = mkLocalId name ty'
1089 ; extendIfaceIdEnv [id] (thing_inside id) }
1090 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1091 = bindIfaceTyVar bndr thing_inside
1093 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1094 bindIfaceBndrs [] thing_inside = thing_inside []
1095 bindIfaceBndrs (b:bs) thing_inside
1096 = bindIfaceBndr b $ \ b' ->
1097 bindIfaceBndrs bs $ \ bs' ->
1098 thing_inside (b':bs')
1100 -----------------------
1101 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1102 tcIfaceLetBndr (IfLetBndr fs ty info)
1103 = do { name <- newIfaceName (mkVarOccFS fs)
1104 ; ty' <- tcIfaceType ty
1106 NoInfo -> return (mkLocalId name ty')
1107 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1109 -- Similar to tcIdInfo, but much simpler
1110 tc_info [] = vanillaIdInfo
1111 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1112 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1113 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1114 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1115 (ppr other) (tc_info i)
1117 -----------------------
1118 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1119 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1120 = do { mod <- getIfModule
1121 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1122 ; ty' <- tcIfaceType ty
1123 ; return (mkLocalId name ty') }
1125 -----------------------
1126 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1127 bindIfaceTyVar (occ,kind) thing_inside
1128 = do { name <- newIfaceName (mkTyVarOcc occ)
1129 ; tyvar <- mk_iface_tyvar name kind
1130 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1132 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1133 bindIfaceTyVars bndrs thing_inside
1134 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1135 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1136 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1138 (occs,kinds) = unzip bndrs
1140 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1141 mk_iface_tyvar name ifKind
1142 = do { kind <- tcIfaceType ifKind
1143 ; if isCoercionKind kind then
1144 return (Var.mkCoVar name kind)
1146 return (Var.mkTyVar name kind) }