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 -- Remember, tycon is the representation tycon
498 ; let orig_res_ty = mkFamilyTyConApp tycon
499 (substTyVars (mkTopTvSubst eq_spec) univ_tyvars)
501 ; buildDataCon name is_infix {- Not infix -}
503 univ_tyvars ex_tyvars
505 arg_tys orig_res_ty tycon
507 mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
509 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
513 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
514 ; ty <- tcIfaceType if_ty
518 Note [Synonym kind loop]
519 ~~~~~~~~~~~~~~~~~~~~~~~~
520 Notice that we eagerly grab the *kind* from the interface file, but
521 build a forkM thunk for the *rhs* (and family stuff). To see why,
522 consider this (Trac #2412)
524 M.hs: module M where { import X; data T = MkT S }
525 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
526 M.hs-boot: module M where { data T }
528 When kind-checking M.hs we need S's kind. But we do not want to
529 find S's kind from (typeKind S-rhs), because we don't want to look at
530 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
531 be defined, and we must not do that until we've finished with M.T.
533 Solution: record S's kind in the interface file; now we can safely
536 %************************************************************************
540 %************************************************************************
543 tcIfaceInst :: IfaceInst -> IfL Instance
544 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
545 ifInstCls = cls, ifInstTys = mb_tcs })
546 = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
547 tcIfaceExtId dfun_occ
548 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
549 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
551 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
552 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
553 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
554 -- { tycon' <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
555 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
556 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
558 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
559 return (mkImportedFamInst fam mb_tcs' tycon')
563 %************************************************************************
567 %************************************************************************
569 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
570 are in the type environment. However, remember that typechecking a Rule may
571 (as a side effect) augment the type envt, and so we may need to iterate the process.
574 tcIfaceRules :: Bool -- True <=> ignore rules
577 tcIfaceRules ignore_prags if_rules
578 | ignore_prags = return []
579 | otherwise = mapM tcIfaceRule if_rules
581 tcIfaceRule :: IfaceRule -> IfL CoreRule
582 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
583 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
584 = do { ~(bndrs', args', rhs') <-
585 -- Typecheck the payload lazily, in the hope it'll never be looked at
586 forkM (ptext (sLit "Rule") <+> ftext name) $
587 bindIfaceBndrs bndrs $ \ bndrs' ->
588 do { args' <- mapM tcIfaceExpr args
589 ; rhs' <- tcIfaceExpr rhs
590 ; return (bndrs', args', rhs') }
591 ; let mb_tcs = map ifTopFreeName args
592 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
593 ru_bndrs = bndrs', ru_args = args',
596 ru_local = False }) } -- An imported RULE is never for a local Id
597 -- or, even if it is (module loop, perhaps)
598 -- we'll just leave it in the non-local set
600 -- This function *must* mirror exactly what Rules.topFreeName does
601 -- We could have stored the ru_rough field in the iface file
602 -- but that would be redundant, I think.
603 -- The only wrinkle is that we must not be deceived by
604 -- type syononyms at the top of a type arg. Since
605 -- we can't tell at this point, we are careful not
606 -- to write them out in coreRuleToIfaceRule
607 ifTopFreeName :: IfaceExpr -> Maybe Name
608 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
609 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
610 ifTopFreeName (IfaceExt n) = Just n
611 ifTopFreeName _ = Nothing
615 %************************************************************************
617 Vectorisation information
619 %************************************************************************
622 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
623 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
624 { ifaceVectInfoVar = vars
625 , ifaceVectInfoTyCon = tycons
626 , ifaceVectInfoTyConReuse = tyconsReuse
628 = do { vVars <- mapM vectVarMapping vars
629 ; tyConRes1 <- mapM vectTyConMapping tycons
630 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
631 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
633 { vectInfoVar = mkVarEnv vVars
634 , vectInfoTyCon = mkNameEnv vTyCons
635 , vectInfoDataCon = mkNameEnv (concat vDataCons)
636 , vectInfoPADFun = mkNameEnv vPAs
637 , vectInfoIso = mkNameEnv vIsos
642 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
643 ; let { var = lookupVar name
644 ; vVar = lookupVar vName
646 ; return (var, (var, vVar))
648 vectTyConMapping name
649 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
650 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
651 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
652 ; let { tycon = lookupTyCon name
653 ; vTycon = lookupTyCon vName
654 ; paTycon = lookupVar paName
655 ; isoTycon = lookupVar isoName
657 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
658 ; return ((name, (tycon, vTycon)), -- (T, T_v)
659 vDataCons, -- list of (Ci, Ci_v)
660 (vName, (vTycon, paTycon)), -- (T_v, paT)
661 (name, (tycon, isoTycon))) -- (T, isoT)
663 vectTyConReuseMapping name
664 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
665 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
666 ; let { tycon = lookupTyCon name
667 ; paTycon = lookupVar paName
668 ; isoTycon = lookupVar isoName
669 ; vDataCons = [ (dataConName dc, (dc, dc))
670 | dc <- tyConDataCons tycon]
672 ; return ((name, (tycon, tycon)), -- (T, T)
673 vDataCons, -- list of (Ci, Ci)
674 (name, (tycon, paTycon)), -- (T, paT)
675 (name, (tycon, isoTycon))) -- (T, isoT)
677 vectDataConMapping datacon
678 = do { let name = dataConName datacon
679 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
680 ; let vDataCon = lookupDataCon vName
681 ; return (name, (datacon, vDataCon))
684 lookupVar name = case lookupTypeEnv typeEnv name of
685 Just (AnId var) -> var
687 panic "TcIface.tcIfaceVectInfo: not an id"
689 panic "TcIface.tcIfaceVectInfo: unknown name"
690 lookupTyCon name = case lookupTypeEnv typeEnv name of
691 Just (ATyCon tc) -> tc
693 panic "TcIface.tcIfaceVectInfo: not a tycon"
695 panic "TcIface.tcIfaceVectInfo: unknown name"
696 lookupDataCon name = case lookupTypeEnv typeEnv name of
697 Just (ADataCon dc) -> dc
699 panic "TcIface.tcIfaceVectInfo: not a datacon"
701 panic "TcIface.tcIfaceVectInfo: unknown name"
704 %************************************************************************
708 %************************************************************************
711 tcIfaceType :: IfaceType -> IfL Type
712 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
713 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
714 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
715 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
716 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
717 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
719 tcIfaceTypes :: [IfaceType] -> IfL [Type]
720 tcIfaceTypes tys = mapM tcIfaceType tys
722 -----------------------------------------
723 tcIfacePredType :: IfacePredType -> IfL PredType
724 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
725 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
726 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
728 -----------------------------------------
729 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
730 tcIfaceCtxt sts = mapM tcIfacePredType sts
734 %************************************************************************
738 %************************************************************************
741 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
742 tcIfaceExpr (IfaceType ty)
743 = Type <$> tcIfaceType ty
745 tcIfaceExpr (IfaceLcl name)
746 = Var <$> tcIfaceLclId name
748 tcIfaceExpr (IfaceTick modName tickNo)
749 = Var <$> tcIfaceTick modName tickNo
751 tcIfaceExpr (IfaceExt gbl)
752 = Var <$> tcIfaceExtId gbl
754 tcIfaceExpr (IfaceLit lit)
757 tcIfaceExpr (IfaceFCall cc ty) = do
758 ty' <- tcIfaceType ty
760 return (Var (mkFCallId u cc ty'))
762 tcIfaceExpr (IfaceTuple boxity args) = do
763 args' <- mapM tcIfaceExpr args
764 -- Put the missing type arguments back in
765 let con_args = map (Type . exprType) args' ++ args'
766 return (mkApps (Var con_id) con_args)
769 con_id = dataConWorkId (tupleCon boxity arity)
772 tcIfaceExpr (IfaceLam bndr body)
773 = bindIfaceBndr bndr $ \bndr' ->
774 Lam bndr' <$> tcIfaceExpr body
776 tcIfaceExpr (IfaceApp fun arg)
777 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
779 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
780 scrut' <- tcIfaceExpr scrut
781 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
783 scrut_ty = exprType scrut'
784 case_bndr' = mkLocalId case_bndr_name scrut_ty
785 tc_app = splitTyConApp scrut_ty
786 -- NB: Won't always succeed (polymoprhic case)
787 -- but won't be demanded in those cases
788 -- NB: not tcSplitTyConApp; we are looking at Core here
789 -- look through non-rec newtypes to find the tycon that
790 -- corresponds to the datacon in this case alternative
792 extendIfaceIdEnv [case_bndr'] $ do
793 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
794 ty' <- tcIfaceType ty
795 return (Case scrut' case_bndr' ty' alts')
797 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
798 rhs' <- tcIfaceExpr rhs
799 id <- tcIfaceLetBndr bndr
800 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
801 return (Let (NonRec id rhs') body')
803 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
804 ids <- mapM tcIfaceLetBndr bndrs
805 extendIfaceIdEnv ids $ do
806 rhss' <- mapM tcIfaceExpr rhss
807 body' <- tcIfaceExpr body
808 return (Let (Rec (ids `zip` rhss')) body')
810 (bndrs, rhss) = unzip pairs
812 tcIfaceExpr (IfaceCast expr co) = do
813 expr' <- tcIfaceExpr expr
814 co' <- tcIfaceType co
815 return (Cast expr' co')
817 tcIfaceExpr (IfaceNote note expr) = do
818 expr' <- tcIfaceExpr expr
820 IfaceInlineMe -> return (Note InlineMe expr')
821 IfaceSCC cc -> return (Note (SCC cc) expr')
822 IfaceCoreNote n -> return (Note (CoreNote n) expr')
824 -------------------------
825 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
826 -> (IfaceConAlt, [FastString], IfaceExpr)
827 -> IfL (AltCon, [TyVar], CoreExpr)
828 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
829 = ASSERT( null names ) do
830 rhs' <- tcIfaceExpr rhs
831 return (DEFAULT, [], rhs')
833 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
834 = ASSERT( null names ) do
835 rhs' <- tcIfaceExpr rhs
836 return (LitAlt lit, [], rhs')
838 -- A case alternative is made quite a bit more complicated
839 -- by the fact that we omit type annotations because we can
840 -- work them out. True enough, but its not that easy!
841 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
842 = do { con <- tcIfaceDataCon data_occ
843 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
844 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
845 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
847 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
848 = ASSERT( isTupleTyCon tycon )
849 do { let [data_con] = tyConDataCons tycon
850 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
852 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
853 -> IfL (AltCon, [TyVar], CoreExpr)
854 tcIfaceDataAlt con inst_tys arg_strs rhs
855 = do { us <- newUniqueSupply
856 ; let uniqs = uniqsFromSupply us
857 ; let (ex_tvs, co_tvs, arg_ids)
858 = dataConRepFSInstPat arg_strs uniqs con inst_tys
859 all_tvs = ex_tvs ++ co_tvs
861 ; rhs' <- extendIfaceTyVarEnv all_tvs $
862 extendIfaceIdEnv arg_ids $
864 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
869 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
870 tcExtCoreBindings [] = return []
871 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
873 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
874 do_one (IfaceNonRec bndr rhs) thing_inside
875 = do { rhs' <- tcIfaceExpr rhs
876 ; bndr' <- newExtCoreBndr bndr
877 ; extendIfaceIdEnv [bndr'] $ do
878 { core_binds <- thing_inside
879 ; return (NonRec bndr' rhs' : core_binds) }}
881 do_one (IfaceRec pairs) thing_inside
882 = do { bndrs' <- mapM newExtCoreBndr bndrs
883 ; extendIfaceIdEnv bndrs' $ do
884 { rhss' <- mapM tcIfaceExpr rhss
885 ; core_binds <- thing_inside
886 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
888 (bndrs,rhss) = unzip pairs
892 %************************************************************************
896 %************************************************************************
899 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
900 tcIdInfo ignore_prags name ty info
901 | ignore_prags = return vanillaIdInfo
902 | otherwise = case info of
903 NoInfo -> return vanillaIdInfo
904 HasInfo info -> foldlM tcPrag init_info info
906 -- Set the CgInfo to something sensible but uninformative before
907 -- we start; default assumption is that it has CAFs
908 init_info = vanillaIdInfo
910 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
911 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
912 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
913 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
915 -- The next two are lazy, so they don't transitively suck stuff in
916 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
917 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
918 tcPrag info (HsUnfold expr) = do
919 maybe_expr' <- tcPragExpr name expr
921 -- maybe_expr' doesn't get looked at if the unfolding
922 -- is never inspected; so the typecheck doesn't even happen
923 unfold_info = case maybe_expr' of
924 Nothing -> noUnfolding
925 Just expr' -> mkTopUnfolding expr'
926 return (info `setUnfoldingInfoLazily` unfold_info)
930 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
931 tcWorkerInfo ty info wkr arity
932 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
934 -- We return without testing maybe_wkr_id, but as soon as info is
935 -- looked at we will test it. That's ok, because its outside the
936 -- knot; and there seems no big reason to further defer the
937 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
938 -- over the unfolding until it's actually used does seem worth while.)
939 ; us <- newUniqueSupply
941 ; return (case mb_wkr_id of
943 Just wkr_id -> add_wkr_info us wkr_id info) }
945 doc = text "Worker for" <+> ppr wkr
946 add_wkr_info us wkr_id info
947 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
948 `setWorkerInfo` HasWorker wkr_id arity
950 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
952 -- We are relying here on strictness info always appearing
953 -- before worker info, fingers crossed ....
954 strict_sig = case newStrictnessInfo info of
956 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
959 For unfoldings we try to do the job lazily, so that we never type check
960 an unfolding that isn't going to be looked at.
963 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
965 = forkM_maybe doc $ do
966 core_expr' <- tcIfaceExpr expr
968 -- Check for type consistency in the unfolding
969 ifOptM Opt_DoCoreLinting $ do
970 in_scope <- get_in_scope_ids
971 case lintUnfolding noSrcLoc in_scope core_expr' of
973 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
977 doc = text "Unfolding of" <+> ppr name
978 get_in_scope_ids -- Urgh; but just for linting
980 do { env <- getGblEnv
981 ; case if_rec_types env of {
982 Nothing -> return [] ;
983 Just (_, get_env) -> do
984 { type_env <- get_env
985 ; return (typeEnvIds type_env) }}}
990 %************************************************************************
992 Getting from Names to TyThings
994 %************************************************************************
997 tcIfaceGlobal :: Name -> IfL TyThing
999 | Just thing <- wiredInNameTyThing_maybe name
1000 -- Wired-in things include TyCons, DataCons, and Ids
1001 = do { ifCheckWiredInThing name; return thing }
1003 = do { env <- getGblEnv
1004 ; case if_rec_types env of { -- Note [Tying the knot]
1005 Just (mod, get_type_env)
1006 | nameIsLocalOrFrom mod name
1007 -> do -- It's defined in the module being compiled
1008 { type_env <- setLclEnv () get_type_env -- yuk
1009 ; case lookupNameEnv type_env name of
1010 Just thing -> return thing
1011 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
1012 (ppr name $$ ppr type_env) }
1016 { hsc_env <- getTopEnv
1017 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1018 ; case mb_thing of {
1019 Just thing -> return thing ;
1022 { mb_thing <- importDecl name -- It's imported; go get it
1024 Failed err -> failIfM err
1025 Succeeded thing -> return thing
1028 -- Note [Tying the knot]
1029 -- ~~~~~~~~~~~~~~~~~~~~~
1030 -- The if_rec_types field is used in two situations:
1032 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1033 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1034 -- after we've built M's type envt.
1036 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1037 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1038 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1040 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1041 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1042 -- emasculated form (e.g. lacking data constructors).
1044 ifCheckWiredInThing :: Name -> IfL ()
1045 -- Even though we are in an interface file, we want to make
1046 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1047 -- Ditto want to ensure that RULES are loaded too
1048 -- See Note [Loading instances] in LoadIface
1049 ifCheckWiredInThing name
1050 = do { mod <- getIfModule
1051 -- Check whether we are typechecking the interface for this
1052 -- very module. E.g when compiling the base library in --make mode
1053 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1054 -- the HPT, so without the test we'll demand-load it into the PIT!
1055 -- C.f. the same test in checkWiredInTyCon above
1056 ; ASSERT2( isExternalName name, ppr name )
1057 unless (mod == nameModule name)
1058 (loadWiredInHomeIface name) }
1060 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1061 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1062 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1063 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1064 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1065 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1066 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1067 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1068 ; return (check_tc (tyThingTyCon thing)) }
1071 | debugIsOn = case toIfaceTyCon tc of
1073 _ -> pprTrace "check_tc" (ppr tc) tc
1075 -- we should be okay just returning Kind constructors without extra loading
1076 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1077 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1078 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1079 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1080 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1082 -- Even though we are in an interface file, we want to make
1083 -- sure the instances and RULES of this tycon are loaded
1084 -- Imagine: f :: Double -> Double
1085 tcWiredInTyCon :: TyCon -> IfL TyCon
1086 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1089 tcIfaceClass :: Name -> IfL Class
1090 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1091 ; return (tyThingClass thing) }
1093 tcIfaceDataCon :: Name -> IfL DataCon
1094 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1096 ADataCon dc -> return dc
1097 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1099 tcIfaceExtId :: Name -> IfL Id
1100 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1102 AnId id -> return id
1103 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1106 %************************************************************************
1110 %************************************************************************
1113 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1114 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1115 = do { name <- newIfaceName (mkVarOccFS fs)
1116 ; ty' <- tcIfaceType ty
1117 ; let id = mkLocalId name ty'
1118 ; extendIfaceIdEnv [id] (thing_inside id) }
1119 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1120 = bindIfaceTyVar bndr thing_inside
1122 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1123 bindIfaceBndrs [] thing_inside = thing_inside []
1124 bindIfaceBndrs (b:bs) thing_inside
1125 = bindIfaceBndr b $ \ b' ->
1126 bindIfaceBndrs bs $ \ bs' ->
1127 thing_inside (b':bs')
1129 -----------------------
1130 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1131 tcIfaceLetBndr (IfLetBndr fs ty info)
1132 = do { name <- newIfaceName (mkVarOccFS fs)
1133 ; ty' <- tcIfaceType ty
1135 NoInfo -> return (mkLocalId name ty')
1136 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1138 -- Similar to tcIdInfo, but much simpler
1139 tc_info [] = vanillaIdInfo
1140 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1141 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1142 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1143 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1144 (ppr other) (tc_info i)
1146 -----------------------
1147 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1148 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1149 = do { mod <- getIfModule
1150 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1151 ; ty' <- tcIfaceType ty
1152 ; return (mkLocalId name ty') }
1154 -----------------------
1155 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1156 bindIfaceTyVar (occ,kind) thing_inside
1157 = do { name <- newIfaceName (mkTyVarOccFS occ)
1158 ; tyvar <- mk_iface_tyvar name kind
1159 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1161 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1162 bindIfaceTyVars bndrs thing_inside
1163 = do { names <- newIfaceNames (map mkTyVarOccFS occs)
1164 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1165 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1167 (occs,kinds) = unzip bndrs
1169 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1170 mk_iface_tyvar name ifKind
1171 = do { kind <- tcIfaceType ifKind
1172 ; if isCoercionKind kind then
1173 return (Var.mkCoVar name kind)
1175 return (Var.mkTyVar name kind) }