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 ; ASSERT( isExternalName tc_name )
131 unless (mod == nameModule tc_name)
132 (initIfaceTcRn (loadWiredInHomeIface tc_name))
133 -- Don't look for (non-existent) Float.hi when
134 -- compiling Float.lhs, which mentions Float of course
135 -- A bit yukky to call initIfaceTcRn here
138 tc_name = tyConName tc
140 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
141 -- Get the TyThing for this Name from an interface file
142 -- It's not a wired-in thing -- the caller caught that
144 = ASSERT( not (isWiredInName name) )
147 -- Load the interface, which should populate the PTE
148 ; mb_iface <- ASSERT2( isExternalName name, ppr name )
149 loadInterface nd_doc (nameModule name) ImportBySystem
151 Failed err_msg -> return (Failed err_msg) ;
154 -- Now look it up again; this time we should find it
156 ; case lookupTypeEnv (eps_PTE eps) name of
157 Just thing -> return (Succeeded thing)
158 Nothing -> return (Failed not_found_msg)
161 nd_doc = ptext (sLit "Need decl for") <+> ppr name
162 not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
163 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
164 2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
165 ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
168 %************************************************************************
170 Type-checking a complete interface
172 %************************************************************************
174 Suppose we discover we don't need to recompile. Then we must type
175 check the old interface file. This is a bit different to the
176 incremental type checking we do as we suck in interface files. Instead
177 we do things similarly as when we are typechecking source decls: we
178 bring into scope the type envt for the interface all at once, using a
179 knot. Remember, the decls aren't necessarily in dependency order --
180 and even if they were, the type decls might be mutually recursive.
183 typecheckIface :: ModIface -- Get the decls from here
184 -> TcRnIf gbl lcl ModDetails
186 = initIfaceTc iface $ \ tc_env_var -> do
187 -- The tc_env_var is freshly allocated, private to
188 -- type-checking this particular interface
189 { -- Get the right set of decls and rules. If we are compiling without -O
190 -- we discard pragmas before typechecking, so that we don't "see"
191 -- information that we shouldn't. From a versioning point of view
192 -- It's not actually *wrong* to do so, but in fact GHCi is unable
193 -- to handle unboxed tuples, so it must not see unfoldings.
194 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
196 -- Typecheck the decls. This is done lazily, so that the knot-tying
197 -- within this single module work out right. In the If monad there is
198 -- no global envt for the current interface; instead, the knot is tied
199 -- through the if_rec_types field of IfGblEnv
200 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
201 ; let type_env = mkNameEnv names_w_things
202 ; writeMutVar tc_env_var type_env
204 -- Now do those rules and instances
205 ; insts <- mapM tcIfaceInst (mi_insts iface)
206 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
207 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
209 -- Vectorisation information
210 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
214 ; exports <- ifaceExportNames (mi_exports iface)
217 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
218 text "Type envt:" <+> ppr type_env])
219 ; return $ ModDetails { md_types = type_env
221 , md_fam_insts = fam_insts
223 , md_vect_info = vect_info
224 , md_exports = exports
230 %************************************************************************
232 Type and class declarations
234 %************************************************************************
237 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
238 -- Load the hi-boot iface for the module being compiled,
239 -- if it indeed exists in the transitive closure of imports
240 -- Return the ModDetails, empty if no hi-boot iface
241 tcHiBootIface hsc_src mod
242 | isHsBoot hsc_src -- Already compiling a hs-boot file
243 = return emptyModDetails
245 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
248 ; if not (isOneShot mode)
249 -- In --make and interactive mode, if this module has an hs-boot file
250 -- we'll have compiled it already, and it'll be in the HPT
252 -- We check wheher the interface is a *boot* interface.
253 -- It can happen (when using GHC from Visual Studio) that we
254 -- compile a module in TypecheckOnly mode, with a stable,
255 -- fully-populated HPT. In that case the boot interface isn't there
256 -- (it's been replaced by the mother module) so we can't check it.
257 -- And that's fine, because if M's ModInfo is in the HPT, then
258 -- it's been compiled once, and we don't need to check the boot iface
259 then do { hpt <- getHpt
260 ; case lookupUFM hpt (moduleName mod) of
261 Just info | mi_boot (hm_iface info)
262 -> return (hm_details info)
263 _ -> return emptyModDetails }
266 -- OK, so we're in one-shot mode.
267 -- In that case, we're read all the direct imports by now,
268 -- so eps_is_boot will record if any of our imports mention us by
269 -- way of hi-boot file
271 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
272 Nothing -> return emptyModDetails ; -- The typical case
274 Just (_, False) -> failWithTc moduleLoop ;
275 -- Someone below us imported us!
276 -- This is a loop with no hi-boot in the way
278 Just (_mod, True) -> -- There's a hi-boot interface below us
280 do { read_result <- findAndReadIface
284 ; case read_result of
285 Failed err -> failWithTc (elaborate err)
286 Succeeded (iface, _path) -> typecheckIface iface
289 need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
290 <+> ptext (sLit "to compare against the Real Thing")
292 moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod)
293 <+> ptext (sLit "depends on itself")
295 elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+>
296 quotes (ppr mod) <> colon) 4 err
300 %************************************************************************
302 Type and class declarations
304 %************************************************************************
306 When typechecking a data type decl, we *lazily* (via forkM) typecheck
307 the constructor argument types. This is in the hope that we may never
308 poke on those argument types, and hence may never need to load the
309 interface files for types mentioned in the arg types.
312 data Foo.S = MkS Baz.T
313 Mabye we can get away without even loading the interface for Baz!
315 This is not just a performance thing. Suppose we have
316 data Foo.S = MkS Baz.T
317 data Baz.T = MkT Foo.S
318 (in different interface files, of course).
319 Now, first we load and typecheck Foo.S, and add it to the type envt.
320 If we do explore MkS's argument, we'll load and typecheck Baz.T.
321 If we explore MkT's argument we'll find Foo.S already in the envt.
323 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
324 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
325 which isn't done yet.
327 All very cunning. However, there is a rather subtle gotcha which bit
328 me when developing this stuff. When we typecheck the decl for S, we
329 extend the type envt with S, MkS, and all its implicit Ids. Suppose
330 (a bug, but it happened) that the list of implicit Ids depended in
331 turn on the constructor arg types. Then the following sequence of
333 * we build a thunk <t> for the constructor arg tys
334 * we build a thunk for the extended type environment (depends on <t>)
335 * we write the extended type envt into the global EPS mutvar
337 Now we look something up in the type envt
339 * which reads the global type envt out of the global EPS mutvar
340 * but that depends in turn on <t>
342 It's subtle, because, it'd work fine if we typechecked the constructor args
343 eagerly -- they don't need the extended type envt. They just get the extended
344 type envt by accident, because they look at it later.
346 What this means is that the implicitTyThings MUST NOT DEPEND on any of
351 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
355 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
356 = do { name <- lookupIfaceTop occ_name
357 ; ty <- tcIfaceType iface_type
358 ; info <- tcIdInfo ignore_prags name ty info
359 ; return (AnId (mkVanillaGlobalWithInfo name ty info)) }
361 tcIfaceDecl _ (IfaceData {ifName = occ_name,
363 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
366 ifGeneric = want_generic,
367 ifFamInst = mb_family })
368 = do { tc_name <- lookupIfaceTop occ_name
369 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
371 { tycon <- fixM ( \ tycon -> do
372 { stupid_theta <- tcIfaceCtxt ctxt
375 Nothing -> return Nothing
377 do { famTyCon <- tcIfaceTyCon fam
378 ; insttys <- mapM tcIfaceType tys
379 ; return $ Just (famTyCon, insttys)
381 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
382 ; buildAlgTyCon tc_name tyvars stupid_theta
383 cons is_rec want_generic gadt_syn famInst
385 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
386 ; return (ATyCon tycon)
389 tcIfaceDecl _ (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
390 ifSynRhs = mb_rhs_ty,
391 ifSynKind = kind, ifFamInst = mb_family})
392 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
393 { tc_name <- lookupIfaceTop occ_name
394 ; rhs_kind <- tcIfaceType kind -- Note [Synonym kind loop]
395 ; ~(rhs, fam) <- forkM (mk_doc tc_name) $
396 do { rhs <- tc_syn_rhs rhs_kind mb_rhs_ty
397 ; fam <- tc_syn_fam mb_family
398 ; return (rhs, fam) }
399 ; tycon <- buildSynTyCon tc_name tyvars rhs rhs_kind fam
400 ; return $ ATyCon tycon
403 mk_doc n = ptext (sLit "Type syonym") <+> ppr n
404 tc_syn_rhs kind Nothing = return (OpenSynTyCon kind Nothing)
405 tc_syn_rhs _ (Just ty) = do { rhs_ty <- tcIfaceType ty
406 ; return (SynonymTyCon rhs_ty) }
409 tc_syn_fam (Just (fam, tys))
410 = do { famTyCon <- tcIfaceTyCon fam
411 ; insttys <- mapM tcIfaceType tys
412 ; return $ Just (famTyCon, insttys) }
414 tcIfaceDecl ignore_prags
415 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
416 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
417 ifATs = rdr_ats, ifSigs = rdr_sigs,
419 -- ToDo: in hs-boot files we should really treat abstract classes specially,
420 -- as we do abstract tycons
421 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
422 { cls_name <- lookupIfaceTop occ_name
423 ; ctxt <- tcIfaceCtxt rdr_ctxt
424 ; sigs <- mapM tc_sig rdr_sigs
425 ; fds <- mapM tc_fd rdr_fds
426 ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
427 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
428 ; cls <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
429 ; return (AClass cls) }
431 tc_sig (IfaceClassOp occ dm rdr_ty)
432 = do { op_name <- lookupIfaceTop occ
433 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
434 -- Must be done lazily for just the same reason as the
435 -- type of a data con; to avoid sucking in types that
436 -- it mentions unless it's necessray to do so
437 ; return (op_name, dm, op_ty) }
439 mk_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
441 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
442 ; tvs2' <- mapM tcIfaceTyVar tvs2
443 ; return (tvs1', tvs2') }
445 -- For each AT argument compute the position of the corresponding class
446 -- parameter in the class head. This will later serve as a permutation
447 -- vector when checking the validity of instance declarations.
448 setTyThingPoss (ATyCon tycon) atTyVars =
449 let classTyVars = map fst tv_bndrs
451 . map ((`elemIndex` classTyVars) . fst)
453 -- There will be no Nothing, as we already passed renaming
455 ATyCon (setTyConArgPoss tycon poss)
456 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
458 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
459 = do { name <- lookupIfaceTop rdr_name
460 ; return (ATyCon (mkForeignTyCon name ext_name
463 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
464 tcIfaceDataCons tycon_name tycon _ if_cons
466 IfAbstractTyCon -> return mkAbstractTyConRhs
467 IfOpenDataTyCon -> return mkOpenDataTyConRhs
468 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
469 ; return (mkDataTyConRhs data_cons) }
470 IfNewTyCon con -> do { data_con <- tc_con_decl con
471 ; mkNewTyConRhs tycon_name tycon data_con }
473 tc_con_decl (IfCon { ifConInfix = is_infix,
474 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
475 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
476 ifConArgTys = args, ifConFields = field_lbls,
477 ifConStricts = stricts})
478 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
479 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
480 { name <- lookupIfaceTop occ
481 ; eq_spec <- tcIfaceEqSpec spec
482 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
483 -- At one stage I thought that this context checking *had*
484 -- to be lazy, because of possible mutual recursion between the
485 -- type and the classe:
487 -- class Real a where { toRat :: a -> Ratio Integer }
488 -- data (Real a) => Ratio a = ...
489 -- But now I think that the laziness in checking class ops breaks
490 -- the loop, so no laziness needed
492 -- Read the argument types, but lazily to avoid faulting in
493 -- the component types unless they are really needed
494 ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
495 ; lbl_names <- mapM lookupIfaceTop field_lbls
497 ; buildDataCon name is_infix {- Not infix -}
499 univ_tyvars ex_tyvars
503 mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
505 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
509 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
510 ; ty <- tcIfaceType if_ty
514 Note [Synonym kind loop]
515 ~~~~~~~~~~~~~~~~~~~~~~~~
516 Notice that we eagerly grab the *kind* from the interface file, but
517 build a forkM thunk for the *rhs* (and family stuff). To see why,
518 consider this (Trac #2412)
520 M.hs: module M where { import X; data T = MkT S }
521 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
522 M.hs-boot: module M where { data T }
524 When kind-checking M.hs we need S's kind. But we do not want to
525 find S's kind from (typeKind S-rhs), because we don't want to look at
526 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
527 be defined, and we must not do that until we've finished with M.T.
529 Solution: record S's kind in the interface file; now we can safely
532 %************************************************************************
536 %************************************************************************
539 tcIfaceInst :: IfaceInst -> IfL Instance
540 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
541 ifInstCls = cls, ifInstTys = mb_tcs })
542 = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
543 tcIfaceExtId dfun_occ
544 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
545 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
547 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
548 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
549 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
550 -- { tycon' <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
551 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
552 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
554 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
555 return (mkImportedFamInst fam mb_tcs' tycon')
559 %************************************************************************
563 %************************************************************************
565 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
566 are in the type environment. However, remember that typechecking a Rule may
567 (as a side effect) augment the type envt, and so we may need to iterate the process.
570 tcIfaceRules :: Bool -- True <=> ignore rules
573 tcIfaceRules ignore_prags if_rules
574 | ignore_prags = return []
575 | otherwise = mapM tcIfaceRule if_rules
577 tcIfaceRule :: IfaceRule -> IfL CoreRule
578 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
579 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
580 = do { ~(bndrs', args', rhs') <-
581 -- Typecheck the payload lazily, in the hope it'll never be looked at
582 forkM (ptext (sLit "Rule") <+> ftext name) $
583 bindIfaceBndrs bndrs $ \ bndrs' ->
584 do { args' <- mapM tcIfaceExpr args
585 ; rhs' <- tcIfaceExpr rhs
586 ; return (bndrs', args', rhs') }
587 ; let mb_tcs = map ifTopFreeName args
588 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
589 ru_bndrs = bndrs', ru_args = args',
592 ru_local = False }) } -- An imported RULE is never for a local Id
593 -- or, even if it is (module loop, perhaps)
594 -- we'll just leave it in the non-local set
596 -- This function *must* mirror exactly what Rules.topFreeName does
597 -- We could have stored the ru_rough field in the iface file
598 -- but that would be redundant, I think.
599 -- The only wrinkle is that we must not be deceived by
600 -- type syononyms at the top of a type arg. Since
601 -- we can't tell at this point, we are careful not
602 -- to write them out in coreRuleToIfaceRule
603 ifTopFreeName :: IfaceExpr -> Maybe Name
604 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
605 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
606 ifTopFreeName (IfaceExt n) = Just n
607 ifTopFreeName _ = Nothing
611 %************************************************************************
613 Vectorisation information
615 %************************************************************************
618 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
619 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
620 { ifaceVectInfoVar = vars
621 , ifaceVectInfoTyCon = tycons
622 , ifaceVectInfoTyConReuse = tyconsReuse
624 = do { vVars <- mapM vectVarMapping vars
625 ; tyConRes1 <- mapM vectTyConMapping tycons
626 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
627 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
629 { vectInfoVar = mkVarEnv vVars
630 , vectInfoTyCon = mkNameEnv vTyCons
631 , vectInfoDataCon = mkNameEnv (concat vDataCons)
632 , vectInfoPADFun = mkNameEnv vPAs
633 , vectInfoIso = mkNameEnv vIsos
638 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
639 ; let { var = lookupVar name
640 ; vVar = lookupVar vName
642 ; return (var, (var, vVar))
644 vectTyConMapping name
645 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
646 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
647 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
648 ; let { tycon = lookupTyCon name
649 ; vTycon = lookupTyCon vName
650 ; paTycon = lookupVar paName
651 ; isoTycon = lookupVar isoName
653 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
654 ; return ((name, (tycon, vTycon)), -- (T, T_v)
655 vDataCons, -- list of (Ci, Ci_v)
656 (vName, (vTycon, paTycon)), -- (T_v, paT)
657 (name, (tycon, isoTycon))) -- (T, isoT)
659 vectTyConReuseMapping name
660 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
661 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
662 ; let { tycon = lookupTyCon name
663 ; paTycon = lookupVar paName
664 ; isoTycon = lookupVar isoName
665 ; vDataCons = [ (dataConName dc, (dc, dc))
666 | dc <- tyConDataCons tycon]
668 ; return ((name, (tycon, tycon)), -- (T, T)
669 vDataCons, -- list of (Ci, Ci)
670 (name, (tycon, paTycon)), -- (T, paT)
671 (name, (tycon, isoTycon))) -- (T, isoT)
673 vectDataConMapping datacon
674 = do { let name = dataConName datacon
675 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
676 ; let vDataCon = lookupDataCon vName
677 ; return (name, (datacon, vDataCon))
680 lookupVar name = case lookupTypeEnv typeEnv name of
681 Just (AnId var) -> var
683 panic "TcIface.tcIfaceVectInfo: not an id"
685 panic "TcIface.tcIfaceVectInfo: unknown name"
686 lookupTyCon name = case lookupTypeEnv typeEnv name of
687 Just (ATyCon tc) -> tc
689 panic "TcIface.tcIfaceVectInfo: not a tycon"
691 panic "TcIface.tcIfaceVectInfo: unknown name"
692 lookupDataCon name = case lookupTypeEnv typeEnv name of
693 Just (ADataCon dc) -> dc
695 panic "TcIface.tcIfaceVectInfo: not a datacon"
697 panic "TcIface.tcIfaceVectInfo: unknown name"
700 %************************************************************************
704 %************************************************************************
707 tcIfaceType :: IfaceType -> IfL Type
708 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
709 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
710 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
711 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
712 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
713 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
715 tcIfaceTypes :: [IfaceType] -> IfL [Type]
716 tcIfaceTypes tys = mapM tcIfaceType tys
718 -----------------------------------------
719 tcIfacePredType :: IfacePredType -> IfL PredType
720 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
721 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
722 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
724 -----------------------------------------
725 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
726 tcIfaceCtxt sts = mapM tcIfacePredType sts
730 %************************************************************************
734 %************************************************************************
737 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
738 tcIfaceExpr (IfaceType ty)
739 = Type <$> tcIfaceType ty
741 tcIfaceExpr (IfaceLcl name)
742 = Var <$> tcIfaceLclId name
744 tcIfaceExpr (IfaceTick modName tickNo)
745 = Var <$> tcIfaceTick modName tickNo
747 tcIfaceExpr (IfaceExt gbl)
748 = Var <$> tcIfaceExtId gbl
750 tcIfaceExpr (IfaceLit lit)
753 tcIfaceExpr (IfaceFCall cc ty) = do
754 ty' <- tcIfaceType ty
756 return (Var (mkFCallId u cc ty'))
758 tcIfaceExpr (IfaceTuple boxity args) = do
759 args' <- mapM tcIfaceExpr args
760 -- Put the missing type arguments back in
761 let con_args = map (Type . exprType) args' ++ args'
762 return (mkApps (Var con_id) con_args)
765 con_id = dataConWorkId (tupleCon boxity arity)
768 tcIfaceExpr (IfaceLam bndr body)
769 = bindIfaceBndr bndr $ \bndr' ->
770 Lam bndr' <$> tcIfaceExpr body
772 tcIfaceExpr (IfaceApp fun arg)
773 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
775 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
776 scrut' <- tcIfaceExpr scrut
777 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
779 scrut_ty = exprType scrut'
780 case_bndr' = mkLocalId case_bndr_name scrut_ty
781 tc_app = splitTyConApp scrut_ty
782 -- NB: Won't always succeed (polymoprhic case)
783 -- but won't be demanded in those cases
784 -- NB: not tcSplitTyConApp; we are looking at Core here
785 -- look through non-rec newtypes to find the tycon that
786 -- corresponds to the datacon in this case alternative
788 extendIfaceIdEnv [case_bndr'] $ do
789 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
790 ty' <- tcIfaceType ty
791 return (Case scrut' case_bndr' ty' alts')
793 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
794 rhs' <- tcIfaceExpr rhs
795 id <- tcIfaceLetBndr bndr
796 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
797 return (Let (NonRec id rhs') body')
799 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
800 ids <- mapM tcIfaceLetBndr bndrs
801 extendIfaceIdEnv ids $ do
802 rhss' <- mapM tcIfaceExpr rhss
803 body' <- tcIfaceExpr body
804 return (Let (Rec (ids `zip` rhss')) body')
806 (bndrs, rhss) = unzip pairs
808 tcIfaceExpr (IfaceCast expr co) = do
809 expr' <- tcIfaceExpr expr
810 co' <- tcIfaceType co
811 return (Cast expr' co')
813 tcIfaceExpr (IfaceNote note expr) = do
814 expr' <- tcIfaceExpr expr
816 IfaceInlineMe -> return (Note InlineMe expr')
817 IfaceSCC cc -> return (Note (SCC cc) expr')
818 IfaceCoreNote n -> return (Note (CoreNote n) expr')
820 -------------------------
821 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
822 -> (IfaceConAlt, [FastString], IfaceExpr)
823 -> IfL (AltCon, [TyVar], CoreExpr)
824 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
825 = ASSERT( null names ) do
826 rhs' <- tcIfaceExpr rhs
827 return (DEFAULT, [], rhs')
829 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
830 = ASSERT( null names ) do
831 rhs' <- tcIfaceExpr rhs
832 return (LitAlt lit, [], rhs')
834 -- A case alternative is made quite a bit more complicated
835 -- by the fact that we omit type annotations because we can
836 -- work them out. True enough, but its not that easy!
837 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
838 = do { con <- tcIfaceDataCon data_occ
839 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
840 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
841 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
843 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
844 = ASSERT( isTupleTyCon tycon )
845 do { let [data_con] = tyConDataCons tycon
846 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
848 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
849 -> IfL (AltCon, [TyVar], CoreExpr)
850 tcIfaceDataAlt con inst_tys arg_strs rhs
851 = do { us <- newUniqueSupply
852 ; let uniqs = uniqsFromSupply us
853 ; let (ex_tvs, co_tvs, arg_ids)
854 = dataConRepFSInstPat arg_strs uniqs con inst_tys
855 all_tvs = ex_tvs ++ co_tvs
857 ; rhs' <- extendIfaceTyVarEnv all_tvs $
858 extendIfaceIdEnv arg_ids $
860 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
865 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
866 tcExtCoreBindings [] = return []
867 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
869 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
870 do_one (IfaceNonRec bndr rhs) thing_inside
871 = do { rhs' <- tcIfaceExpr rhs
872 ; bndr' <- newExtCoreBndr bndr
873 ; extendIfaceIdEnv [bndr'] $ do
874 { core_binds <- thing_inside
875 ; return (NonRec bndr' rhs' : core_binds) }}
877 do_one (IfaceRec pairs) thing_inside
878 = do { bndrs' <- mapM newExtCoreBndr bndrs
879 ; extendIfaceIdEnv bndrs' $ do
880 { rhss' <- mapM tcIfaceExpr rhss
881 ; core_binds <- thing_inside
882 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
884 (bndrs,rhss) = unzip pairs
888 %************************************************************************
892 %************************************************************************
895 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
896 tcIdInfo ignore_prags name ty info
897 | ignore_prags = return vanillaIdInfo
898 | otherwise = case info of
899 NoInfo -> return vanillaIdInfo
900 HasInfo info -> foldlM tcPrag init_info info
902 -- Set the CgInfo to something sensible but uninformative before
903 -- we start; default assumption is that it has CAFs
904 init_info = vanillaIdInfo
906 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
907 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
908 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
909 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
911 -- The next two are lazy, so they don't transitively suck stuff in
912 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
913 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
914 tcPrag info (HsUnfold expr) = do
915 maybe_expr' <- tcPragExpr name expr
917 -- maybe_expr' doesn't get looked at if the unfolding
918 -- is never inspected; so the typecheck doesn't even happen
919 unfold_info = case maybe_expr' of
920 Nothing -> noUnfolding
921 Just expr' -> mkTopUnfolding expr'
922 return (info `setUnfoldingInfoLazily` unfold_info)
926 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
927 tcWorkerInfo ty info wkr arity
928 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
930 -- We return without testing maybe_wkr_id, but as soon as info is
931 -- looked at we will test it. That's ok, because its outside the
932 -- knot; and there seems no big reason to further defer the
933 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
934 -- over the unfolding until it's actually used does seem worth while.)
935 ; us <- newUniqueSupply
937 ; return (case mb_wkr_id of
939 Just wkr_id -> add_wkr_info us wkr_id info) }
941 doc = text "Worker for" <+> ppr wkr
942 add_wkr_info us wkr_id info
943 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
944 `setWorkerInfo` HasWorker wkr_id arity
946 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
948 -- We are relying here on strictness info always appearing
949 -- before worker info, fingers crossed ....
950 strict_sig = case newStrictnessInfo info of
952 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
955 For unfoldings we try to do the job lazily, so that we never type check
956 an unfolding that isn't going to be looked at.
959 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
961 = forkM_maybe doc $ do
962 core_expr' <- tcIfaceExpr expr
964 -- Check for type consistency in the unfolding
965 ifOptM Opt_DoCoreLinting $ do
966 in_scope <- get_in_scope_ids
967 case lintUnfolding noSrcLoc in_scope core_expr' of
969 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
973 doc = text "Unfolding of" <+> ppr name
974 get_in_scope_ids -- Urgh; but just for linting
976 do { env <- getGblEnv
977 ; case if_rec_types env of {
978 Nothing -> return [] ;
979 Just (_, get_env) -> do
980 { type_env <- get_env
981 ; return (typeEnvIds type_env) }}}
986 %************************************************************************
988 Getting from Names to TyThings
990 %************************************************************************
993 tcIfaceGlobal :: Name -> IfL TyThing
995 | Just thing <- wiredInNameTyThing_maybe name
996 -- Wired-in things include TyCons, DataCons, and Ids
997 = do { ifCheckWiredInThing name; return thing }
999 = do { env <- getGblEnv
1000 ; case if_rec_types env of { -- Note [Tying the knot]
1001 Just (mod, get_type_env)
1002 | nameIsLocalOrFrom mod name
1003 -> do -- It's defined in the module being compiled
1004 { type_env <- setLclEnv () get_type_env -- yuk
1005 ; case lookupNameEnv type_env name of
1006 Just thing -> return thing
1007 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
1008 (ppr name $$ ppr type_env) }
1012 { hsc_env <- getTopEnv
1013 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1014 ; case mb_thing of {
1015 Just thing -> return thing ;
1018 { mb_thing <- importDecl name -- It's imported; go get it
1020 Failed err -> failIfM err
1021 Succeeded thing -> return thing
1024 -- Note [Tying the knot]
1025 -- ~~~~~~~~~~~~~~~~~~~~~
1026 -- The if_rec_types field is used in two situations:
1028 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1029 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1030 -- after we've built M's type envt.
1032 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1033 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1034 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1036 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1037 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1038 -- emasculated form (e.g. lacking data constructors).
1040 ifCheckWiredInThing :: Name -> IfL ()
1041 -- Even though we are in an interface file, we want to make
1042 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1043 -- Ditto want to ensure that RULES are loaded too
1044 -- See Note [Loading instances] in LoadIface
1045 ifCheckWiredInThing name
1046 = do { mod <- getIfModule
1047 -- Check whether we are typechecking the interface for this
1048 -- very module. E.g when compiling the base library in --make mode
1049 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1050 -- the HPT, so without the test we'll demand-load it into the PIT!
1051 -- C.f. the same test in checkWiredInTyCon above
1052 ; ASSERT2( isExternalName name, ppr name )
1053 unless (mod == nameModule name)
1054 (loadWiredInHomeIface name) }
1056 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1057 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1058 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1059 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1060 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1061 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1062 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1063 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1064 ; return (check_tc (tyThingTyCon thing)) }
1067 | debugIsOn = case toIfaceTyCon tc of
1069 _ -> pprTrace "check_tc" (ppr tc) tc
1071 -- we should be okay just returning Kind constructors without extra loading
1072 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1073 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1074 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1075 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1076 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1078 -- Even though we are in an interface file, we want to make
1079 -- sure the instances and RULES of this tycon are loaded
1080 -- Imagine: f :: Double -> Double
1081 tcWiredInTyCon :: TyCon -> IfL TyCon
1082 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1085 tcIfaceClass :: Name -> IfL Class
1086 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1087 ; return (tyThingClass thing) }
1089 tcIfaceDataCon :: Name -> IfL DataCon
1090 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1092 ADataCon dc -> return dc
1093 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1095 tcIfaceExtId :: Name -> IfL Id
1096 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1098 AnId id -> return id
1099 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1102 %************************************************************************
1106 %************************************************************************
1109 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1110 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1111 = do { name <- newIfaceName (mkVarOccFS fs)
1112 ; ty' <- tcIfaceType ty
1113 ; let id = mkLocalId name ty'
1114 ; extendIfaceIdEnv [id] (thing_inside id) }
1115 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1116 = bindIfaceTyVar bndr thing_inside
1118 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1119 bindIfaceBndrs [] thing_inside = thing_inside []
1120 bindIfaceBndrs (b:bs) thing_inside
1121 = bindIfaceBndr b $ \ b' ->
1122 bindIfaceBndrs bs $ \ bs' ->
1123 thing_inside (b':bs')
1125 -----------------------
1126 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1127 tcIfaceLetBndr (IfLetBndr fs ty info)
1128 = do { name <- newIfaceName (mkVarOccFS fs)
1129 ; ty' <- tcIfaceType ty
1131 NoInfo -> return (mkLocalId name ty')
1132 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1134 -- Similar to tcIdInfo, but much simpler
1135 tc_info [] = vanillaIdInfo
1136 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1137 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1138 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1139 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1140 (ppr other) (tc_info i)
1142 -----------------------
1143 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1144 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1145 = do { mod <- getIfModule
1146 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1147 ; ty' <- tcIfaceType ty
1148 ; return (mkLocalId name ty') }
1150 -----------------------
1151 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1152 bindIfaceTyVar (occ,kind) thing_inside
1153 = do { name <- newIfaceName (mkTyVarOccFS occ)
1154 ; tyvar <- mk_iface_tyvar name kind
1155 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1157 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1158 bindIfaceTyVars bndrs thing_inside
1159 = do { names <- newIfaceNames (map mkTyVarOccFS occs)
1160 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1161 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1163 (occs,kinds) = unzip bndrs
1165 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1166 mk_iface_tyvar name ifKind
1167 = do { kind <- tcIfaceType ifKind
1168 ; if isCoercionKind kind then
1169 return (Var.mkCoVar name kind)
1171 return (Var.mkTyVar name kind) }