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 (mkVanillaGlobalWithInfo name ty info)) }
359 tcIfaceDecl _ (IfaceData {ifName = occ_name,
361 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
364 ifGeneric = want_generic,
365 ifFamInst = mb_family })
366 = do { tc_name <- lookupIfaceTop occ_name
367 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
369 { tycon <- fixM ( \ tycon -> do
370 { stupid_theta <- tcIfaceCtxt ctxt
373 Nothing -> return Nothing
375 do { famTyCon <- tcIfaceTyCon fam
376 ; insttys <- mapM tcIfaceType tys
377 ; return $ Just (famTyCon, insttys)
379 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
380 ; buildAlgTyCon tc_name tyvars stupid_theta
381 cons is_rec want_generic gadt_syn famInst
383 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
384 ; return (ATyCon tycon)
387 tcIfaceDecl _ (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
388 ifSynRhs = mb_rhs_ty,
389 ifSynKind = kind, ifFamInst = mb_family})
390 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
391 { tc_name <- lookupIfaceTop occ_name
392 ; rhs_kind <- tcIfaceType kind -- Note [Synonym kind loop]
393 ; ~(rhs, fam) <- forkM (mk_doc tc_name) $
394 do { rhs <- tc_syn_rhs rhs_kind mb_rhs_ty
395 ; fam <- tc_syn_fam mb_family
396 ; return (rhs, fam) }
397 ; tycon <- buildSynTyCon tc_name tyvars rhs rhs_kind fam
398 ; return $ ATyCon tycon
401 mk_doc n = ptext (sLit "Type syonym") <+> ppr n
402 tc_syn_rhs kind Nothing = return (OpenSynTyCon kind Nothing)
403 tc_syn_rhs _ (Just ty) = do { rhs_ty <- tcIfaceType ty
404 ; return (SynonymTyCon rhs_ty) }
407 tc_syn_fam (Just (fam, tys))
408 = do { famTyCon <- tcIfaceTyCon fam
409 ; insttys <- mapM tcIfaceType tys
410 ; return $ Just (famTyCon, insttys) }
412 tcIfaceDecl ignore_prags
413 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
414 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
415 ifATs = rdr_ats, ifSigs = rdr_sigs,
417 -- ToDo: in hs-boot files we should really treat abstract classes specially,
418 -- as we do abstract tycons
419 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
420 { cls_name <- lookupIfaceTop occ_name
421 ; ctxt <- tcIfaceCtxt rdr_ctxt
422 ; sigs <- mapM tc_sig rdr_sigs
423 ; fds <- mapM tc_fd rdr_fds
424 ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
425 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
426 ; cls <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
427 ; return (AClass cls) }
429 tc_sig (IfaceClassOp occ dm rdr_ty)
430 = do { op_name <- lookupIfaceTop occ
431 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
432 -- Must be done lazily for just the same reason as the
433 -- type of a data con; to avoid sucking in types that
434 -- it mentions unless it's necessray to do so
435 ; return (op_name, dm, op_ty) }
437 mk_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
439 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
440 ; tvs2' <- mapM tcIfaceTyVar tvs2
441 ; return (tvs1', tvs2') }
443 -- For each AT argument compute the position of the corresponding class
444 -- parameter in the class head. This will later serve as a permutation
445 -- vector when checking the validity of instance declarations.
446 setTyThingPoss (ATyCon tycon) atTyVars =
447 let classTyVars = map fst tv_bndrs
449 . map ((`elemIndex` classTyVars) . fst)
451 -- There will be no Nothing, as we already passed renaming
453 ATyCon (setTyConArgPoss tycon poss)
454 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
456 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
457 = do { name <- lookupIfaceTop rdr_name
458 ; return (ATyCon (mkForeignTyCon name ext_name
461 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
462 tcIfaceDataCons tycon_name tycon _ if_cons
464 IfAbstractTyCon -> return mkAbstractTyConRhs
465 IfOpenDataTyCon -> return mkOpenDataTyConRhs
466 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
467 ; return (mkDataTyConRhs data_cons) }
468 IfNewTyCon con -> do { data_con <- tc_con_decl con
469 ; mkNewTyConRhs tycon_name tycon data_con }
471 tc_con_decl (IfCon { ifConInfix = is_infix,
472 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
473 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
474 ifConArgTys = args, ifConFields = field_lbls,
475 ifConStricts = stricts})
476 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
477 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
478 { name <- lookupIfaceTop occ
479 ; eq_spec <- tcIfaceEqSpec spec
480 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
481 -- At one stage I thought that this context checking *had*
482 -- to be lazy, because of possible mutual recursion between the
483 -- type and the classe:
485 -- class Real a where { toRat :: a -> Ratio Integer }
486 -- data (Real a) => Ratio a = ...
487 -- But now I think that the laziness in checking class ops breaks
488 -- the loop, so no laziness needed
490 -- Read the argument types, but lazily to avoid faulting in
491 -- the component types unless they are really needed
492 ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
493 ; lbl_names <- mapM lookupIfaceTop field_lbls
495 ; buildDataCon name is_infix {- Not infix -}
497 univ_tyvars ex_tyvars
501 mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
503 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
507 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
508 ; ty <- tcIfaceType if_ty
512 Note [Synonym kind loop]
513 ~~~~~~~~~~~~~~~~~~~~~~~~
514 Notice that we eagerly grab the *kind* from the interface file, but
515 build a forkM thunk for the *rhs* (and family stuff). To see why,
516 consider this (Trac #2412)
518 M.hs: module M where { import X; data T = MkT S }
519 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
520 M.hs-boot: module M where { data T }
522 When kind-checking M.hs we need S's kind. But we do not want to
523 find S's kind from (typeKind S-rhs), because we don't want to look at
524 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
525 be defined, and we must not do that until we've finished with M.T.
527 Solution: record S's kind in the interface file; now we can safely
530 %************************************************************************
534 %************************************************************************
537 tcIfaceInst :: IfaceInst -> IfL Instance
538 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
539 ifInstCls = cls, ifInstTys = mb_tcs })
540 = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
541 tcIfaceExtId dfun_occ
542 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
543 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
545 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
546 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
547 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
548 -- { tycon' <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
549 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
550 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
552 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
553 return (mkImportedFamInst fam mb_tcs' tycon')
557 %************************************************************************
561 %************************************************************************
563 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
564 are in the type environment. However, remember that typechecking a Rule may
565 (as a side effect) augment the type envt, and so we may need to iterate the process.
568 tcIfaceRules :: Bool -- True <=> ignore rules
571 tcIfaceRules ignore_prags if_rules
572 | ignore_prags = return []
573 | otherwise = mapM tcIfaceRule if_rules
575 tcIfaceRule :: IfaceRule -> IfL CoreRule
576 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
577 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
578 = do { ~(bndrs', args', rhs') <-
579 -- Typecheck the payload lazily, in the hope it'll never be looked at
580 forkM (ptext (sLit "Rule") <+> ftext name) $
581 bindIfaceBndrs bndrs $ \ bndrs' ->
582 do { args' <- mapM tcIfaceExpr args
583 ; rhs' <- tcIfaceExpr rhs
584 ; return (bndrs', args', rhs') }
585 ; let mb_tcs = map ifTopFreeName args
586 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
587 ru_bndrs = bndrs', ru_args = args',
590 ru_local = False }) } -- An imported RULE is never for a local Id
591 -- or, even if it is (module loop, perhaps)
592 -- we'll just leave it in the non-local set
594 -- This function *must* mirror exactly what Rules.topFreeName does
595 -- We could have stored the ru_rough field in the iface file
596 -- but that would be redundant, I think.
597 -- The only wrinkle is that we must not be deceived by
598 -- type syononyms at the top of a type arg. Since
599 -- we can't tell at this point, we are careful not
600 -- to write them out in coreRuleToIfaceRule
601 ifTopFreeName :: IfaceExpr -> Maybe Name
602 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
603 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
604 ifTopFreeName (IfaceExt n) = Just n
605 ifTopFreeName _ = Nothing
609 %************************************************************************
611 Vectorisation information
613 %************************************************************************
616 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
617 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
618 { ifaceVectInfoVar = vars
619 , ifaceVectInfoTyCon = tycons
620 , ifaceVectInfoTyConReuse = tyconsReuse
622 = do { vVars <- mapM vectVarMapping vars
623 ; tyConRes1 <- mapM vectTyConMapping tycons
624 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
625 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
627 { vectInfoVar = mkVarEnv vVars
628 , vectInfoTyCon = mkNameEnv vTyCons
629 , vectInfoDataCon = mkNameEnv (concat vDataCons)
630 , vectInfoPADFun = mkNameEnv vPAs
631 , vectInfoIso = mkNameEnv vIsos
636 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
637 ; let { var = lookupVar name
638 ; vVar = lookupVar vName
640 ; return (var, (var, vVar))
642 vectTyConMapping name
643 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
644 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
645 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
646 ; let { tycon = lookupTyCon name
647 ; vTycon = lookupTyCon vName
648 ; paTycon = lookupVar paName
649 ; isoTycon = lookupVar isoName
651 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
652 ; return ((name, (tycon, vTycon)), -- (T, T_v)
653 vDataCons, -- list of (Ci, Ci_v)
654 (vName, (vTycon, paTycon)), -- (T_v, paT)
655 (name, (tycon, isoTycon))) -- (T, isoT)
657 vectTyConReuseMapping name
658 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
659 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
660 ; let { tycon = lookupTyCon name
661 ; paTycon = lookupVar paName
662 ; isoTycon = lookupVar isoName
663 ; vDataCons = [ (dataConName dc, (dc, dc))
664 | dc <- tyConDataCons tycon]
666 ; return ((name, (tycon, tycon)), -- (T, T)
667 vDataCons, -- list of (Ci, Ci)
668 (name, (tycon, paTycon)), -- (T, paT)
669 (name, (tycon, isoTycon))) -- (T, isoT)
671 vectDataConMapping datacon
672 = do { let name = dataConName datacon
673 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
674 ; let vDataCon = lookupDataCon vName
675 ; return (name, (datacon, vDataCon))
678 lookupVar name = case lookupTypeEnv typeEnv name of
679 Just (AnId var) -> var
681 panic "TcIface.tcIfaceVectInfo: not an id"
683 panic "TcIface.tcIfaceVectInfo: unknown name"
684 lookupTyCon name = case lookupTypeEnv typeEnv name of
685 Just (ATyCon tc) -> tc
687 panic "TcIface.tcIfaceVectInfo: not a tycon"
689 panic "TcIface.tcIfaceVectInfo: unknown name"
690 lookupDataCon name = case lookupTypeEnv typeEnv name of
691 Just (ADataCon dc) -> dc
693 panic "TcIface.tcIfaceVectInfo: not a datacon"
695 panic "TcIface.tcIfaceVectInfo: unknown name"
698 %************************************************************************
702 %************************************************************************
705 tcIfaceType :: IfaceType -> IfL Type
706 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
707 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
708 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
709 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
710 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
711 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
713 tcIfaceTypes :: [IfaceType] -> IfL [Type]
714 tcIfaceTypes tys = mapM tcIfaceType tys
716 -----------------------------------------
717 tcIfacePredType :: IfacePredType -> IfL PredType
718 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
719 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
720 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
722 -----------------------------------------
723 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
724 tcIfaceCtxt sts = mapM tcIfacePredType sts
728 %************************************************************************
732 %************************************************************************
735 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
736 tcIfaceExpr (IfaceType ty)
737 = Type <$> tcIfaceType ty
739 tcIfaceExpr (IfaceLcl name)
740 = Var <$> tcIfaceLclId name
742 tcIfaceExpr (IfaceTick modName tickNo)
743 = Var <$> tcIfaceTick modName tickNo
745 tcIfaceExpr (IfaceExt gbl)
746 = Var <$> tcIfaceExtId gbl
748 tcIfaceExpr (IfaceLit lit)
751 tcIfaceExpr (IfaceFCall cc ty) = do
752 ty' <- tcIfaceType ty
754 return (Var (mkFCallId u cc ty'))
756 tcIfaceExpr (IfaceTuple boxity args) = do
757 args' <- mapM tcIfaceExpr args
758 -- Put the missing type arguments back in
759 let con_args = map (Type . exprType) args' ++ args'
760 return (mkApps (Var con_id) con_args)
763 con_id = dataConWorkId (tupleCon boxity arity)
766 tcIfaceExpr (IfaceLam bndr body)
767 = bindIfaceBndr bndr $ \bndr' ->
768 Lam bndr' <$> tcIfaceExpr body
770 tcIfaceExpr (IfaceApp fun arg)
771 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
773 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
774 scrut' <- tcIfaceExpr scrut
775 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
777 scrut_ty = exprType scrut'
778 case_bndr' = mkLocalId case_bndr_name scrut_ty
779 tc_app = splitTyConApp scrut_ty
780 -- NB: Won't always succeed (polymoprhic case)
781 -- but won't be demanded in those cases
782 -- NB: not tcSplitTyConApp; we are looking at Core here
783 -- look through non-rec newtypes to find the tycon that
784 -- corresponds to the datacon in this case alternative
786 extendIfaceIdEnv [case_bndr'] $ do
787 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
788 ty' <- tcIfaceType ty
789 return (Case scrut' case_bndr' ty' alts')
791 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
792 rhs' <- tcIfaceExpr rhs
793 id <- tcIfaceLetBndr bndr
794 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
795 return (Let (NonRec id rhs') body')
797 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
798 ids <- mapM tcIfaceLetBndr bndrs
799 extendIfaceIdEnv ids $ do
800 rhss' <- mapM tcIfaceExpr rhss
801 body' <- tcIfaceExpr body
802 return (Let (Rec (ids `zip` rhss')) body')
804 (bndrs, rhss) = unzip pairs
806 tcIfaceExpr (IfaceCast expr co) = do
807 expr' <- tcIfaceExpr expr
808 co' <- tcIfaceType co
809 return (Cast expr' co')
811 tcIfaceExpr (IfaceNote note expr) = do
812 expr' <- tcIfaceExpr expr
814 IfaceInlineMe -> return (Note InlineMe expr')
815 IfaceSCC cc -> return (Note (SCC cc) expr')
816 IfaceCoreNote n -> return (Note (CoreNote n) expr')
818 -------------------------
819 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
820 -> (IfaceConAlt, [FastString], IfaceExpr)
821 -> IfL (AltCon, [TyVar], CoreExpr)
822 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
823 = ASSERT( null names ) do
824 rhs' <- tcIfaceExpr rhs
825 return (DEFAULT, [], rhs')
827 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
828 = ASSERT( null names ) do
829 rhs' <- tcIfaceExpr rhs
830 return (LitAlt lit, [], rhs')
832 -- A case alternative is made quite a bit more complicated
833 -- by the fact that we omit type annotations because we can
834 -- work them out. True enough, but its not that easy!
835 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
836 = do { con <- tcIfaceDataCon data_occ
837 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
838 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
839 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
841 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
842 = ASSERT( isTupleTyCon tycon )
843 do { let [data_con] = tyConDataCons tycon
844 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
846 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
847 -> IfL (AltCon, [TyVar], CoreExpr)
848 tcIfaceDataAlt con inst_tys arg_strs rhs
849 = do { us <- newUniqueSupply
850 ; let uniqs = uniqsFromSupply us
851 ; let (ex_tvs, co_tvs, arg_ids)
852 = dataConRepFSInstPat arg_strs uniqs con inst_tys
853 all_tvs = ex_tvs ++ co_tvs
855 ; rhs' <- extendIfaceTyVarEnv all_tvs $
856 extendIfaceIdEnv arg_ids $
858 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
863 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
864 tcExtCoreBindings [] = return []
865 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
867 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
868 do_one (IfaceNonRec bndr rhs) thing_inside
869 = do { rhs' <- tcIfaceExpr rhs
870 ; bndr' <- newExtCoreBndr bndr
871 ; extendIfaceIdEnv [bndr'] $ do
872 { core_binds <- thing_inside
873 ; return (NonRec bndr' rhs' : core_binds) }}
875 do_one (IfaceRec pairs) thing_inside
876 = do { bndrs' <- mapM newExtCoreBndr bndrs
877 ; extendIfaceIdEnv bndrs' $ do
878 { rhss' <- mapM tcIfaceExpr rhss
879 ; core_binds <- thing_inside
880 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
882 (bndrs,rhss) = unzip pairs
886 %************************************************************************
890 %************************************************************************
893 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
894 tcIdInfo ignore_prags name ty info
895 | ignore_prags = return vanillaIdInfo
896 | otherwise = case info of
897 NoInfo -> return vanillaIdInfo
898 HasInfo info -> foldlM tcPrag init_info info
900 -- Set the CgInfo to something sensible but uninformative before
901 -- we start; default assumption is that it has CAFs
902 init_info = vanillaIdInfo
904 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
905 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
906 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
907 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
909 -- The next two are lazy, so they don't transitively suck stuff in
910 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
911 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
912 tcPrag info (HsUnfold expr) = do
913 maybe_expr' <- tcPragExpr name expr
915 -- maybe_expr' doesn't get looked at if the unfolding
916 -- is never inspected; so the typecheck doesn't even happen
917 unfold_info = case maybe_expr' of
918 Nothing -> noUnfolding
919 Just expr' -> mkTopUnfolding expr'
920 return (info `setUnfoldingInfoLazily` unfold_info)
924 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
925 tcWorkerInfo ty info wkr arity
926 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
928 -- We return without testing maybe_wkr_id, but as soon as info is
929 -- looked at we will test it. That's ok, because its outside the
930 -- knot; and there seems no big reason to further defer the
931 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
932 -- over the unfolding until it's actually used does seem worth while.)
933 ; us <- newUniqueSupply
935 ; return (case mb_wkr_id of
937 Just wkr_id -> add_wkr_info us wkr_id info) }
939 doc = text "Worker for" <+> ppr wkr
940 add_wkr_info us wkr_id info
941 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
942 `setWorkerInfo` HasWorker wkr_id arity
944 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
946 -- We are relying here on strictness info always appearing
947 -- before worker info, fingers crossed ....
948 strict_sig = case newStrictnessInfo info of
950 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
953 For unfoldings we try to do the job lazily, so that we never type check
954 an unfolding that isn't going to be looked at.
957 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
959 = forkM_maybe doc $ do
960 core_expr' <- tcIfaceExpr expr
962 -- Check for type consistency in the unfolding
963 ifOptM Opt_DoCoreLinting $ do
964 in_scope <- get_in_scope_ids
965 case lintUnfolding noSrcLoc in_scope core_expr' of
967 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
971 doc = text "Unfolding of" <+> ppr name
972 get_in_scope_ids -- Urgh; but just for linting
974 do { env <- getGblEnv
975 ; case if_rec_types env of {
976 Nothing -> return [] ;
977 Just (_, get_env) -> do
978 { type_env <- get_env
979 ; return (typeEnvIds type_env) }}}
984 %************************************************************************
986 Getting from Names to TyThings
988 %************************************************************************
991 tcIfaceGlobal :: Name -> IfL TyThing
993 | Just thing <- wiredInNameTyThing_maybe name
994 -- Wired-in things include TyCons, DataCons, and Ids
995 = do { ifCheckWiredInThing name; return thing }
997 = do { env <- getGblEnv
998 ; case if_rec_types env of { -- Note [Tying the knot]
999 Just (mod, get_type_env)
1000 | nameIsLocalOrFrom mod name
1001 -> do -- It's defined in the module being compiled
1002 { type_env <- setLclEnv () get_type_env -- yuk
1003 ; case lookupNameEnv type_env name of
1004 Just thing -> return thing
1005 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
1006 (ppr name $$ ppr type_env) }
1010 { hsc_env <- getTopEnv
1011 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1012 ; case mb_thing of {
1013 Just thing -> return thing ;
1016 { mb_thing <- importDecl name -- It's imported; go get it
1018 Failed err -> failIfM err
1019 Succeeded thing -> return thing
1022 -- Note [Tying the knot]
1023 -- ~~~~~~~~~~~~~~~~~~~~~
1024 -- The if_rec_types field is used in two situations:
1026 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1027 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1028 -- after we've built M's type envt.
1030 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1031 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1032 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1034 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1035 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1036 -- emasculated form (e.g. lacking data constructors).
1038 ifCheckWiredInThing :: Name -> IfL ()
1039 -- Even though we are in an interface file, we want to make
1040 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1041 -- Ditto want to ensure that RULES are loaded too
1042 -- See Note [Loading instances] in LoadIface
1043 ifCheckWiredInThing name
1044 = do { mod <- getIfModule
1045 -- Check whether we are typechecking the interface for this
1046 -- very module. E.g when compiling the base library in --make mode
1047 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1048 -- the HPT, so without the test we'll demand-load it into the PIT!
1049 -- C.f. the same test in checkWiredInTyCon above
1050 ; unless (mod == nameModule name)
1051 (loadWiredInHomeIface name) }
1053 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1054 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1055 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1056 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1057 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1058 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1059 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1060 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1061 ; return (check_tc (tyThingTyCon thing)) }
1064 | debugIsOn = case toIfaceTyCon tc of
1066 _ -> pprTrace "check_tc" (ppr tc) tc
1068 -- we should be okay just returning Kind constructors without extra loading
1069 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1070 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1071 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1072 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1073 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1075 -- Even though we are in an interface file, we want to make
1076 -- sure the instances and RULES of this tycon are loaded
1077 -- Imagine: f :: Double -> Double
1078 tcWiredInTyCon :: TyCon -> IfL TyCon
1079 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1082 tcIfaceClass :: Name -> IfL Class
1083 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1084 ; return (tyThingClass thing) }
1086 tcIfaceDataCon :: Name -> IfL DataCon
1087 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1089 ADataCon dc -> return dc
1090 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1092 tcIfaceExtId :: Name -> IfL Id
1093 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1095 AnId id -> return id
1096 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1099 %************************************************************************
1103 %************************************************************************
1106 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1107 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1108 = do { name <- newIfaceName (mkVarOccFS fs)
1109 ; ty' <- tcIfaceType ty
1110 ; let id = mkLocalId name ty'
1111 ; extendIfaceIdEnv [id] (thing_inside id) }
1112 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1113 = bindIfaceTyVar bndr thing_inside
1115 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1116 bindIfaceBndrs [] thing_inside = thing_inside []
1117 bindIfaceBndrs (b:bs) thing_inside
1118 = bindIfaceBndr b $ \ b' ->
1119 bindIfaceBndrs bs $ \ bs' ->
1120 thing_inside (b':bs')
1122 -----------------------
1123 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1124 tcIfaceLetBndr (IfLetBndr fs ty info)
1125 = do { name <- newIfaceName (mkVarOccFS fs)
1126 ; ty' <- tcIfaceType ty
1128 NoInfo -> return (mkLocalId name ty')
1129 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1131 -- Similar to tcIdInfo, but much simpler
1132 tc_info [] = vanillaIdInfo
1133 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1134 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1135 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1136 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1137 (ppr other) (tc_info i)
1139 -----------------------
1140 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1141 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1142 = do { mod <- getIfModule
1143 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1144 ; ty' <- tcIfaceType ty
1145 ; return (mkLocalId name ty') }
1147 -----------------------
1148 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1149 bindIfaceTyVar (occ,kind) thing_inside
1150 = do { name <- newIfaceName (mkTyVarOccFS occ)
1151 ; tyvar <- mk_iface_tyvar name kind
1152 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1154 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1155 bindIfaceTyVars bndrs thing_inside
1156 = do { names <- newIfaceNames (map mkTyVarOccFS occs)
1157 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1158 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1160 (occs,kinds) = unzip bndrs
1162 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1163 mk_iface_tyvar name ifKind
1164 = do { kind <- tcIfaceType ifKind
1165 ; if isCoercionKind kind then
1166 return (Var.mkCoVar name kind)
1168 return (Var.mkTyVar name kind) }