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, tcIfaceAnnotations, tcIfaceGlobal, tcExtCoreBindings
15 #include "HsVersions.h"
56 import BasicTypes (Arity)
69 An IfaceDecl is populated with RdrNames, and these are not renamed to
70 Names before typechecking, because there should be no scope errors etc.
72 -- For (b) consider: f = \$(...h....)
73 -- where h is imported, and calls f via an hi-boot file.
74 -- This is bad! But it is not seen as a staging error, because h
75 -- is indeed imported. We don't want the type-checker to black-hole
76 -- when simplifying and compiling the splice!
78 -- Simple solution: discard any unfolding that mentions a variable
79 -- bound in this module (and hence not yet processed).
80 -- The discarding happens when forkM finds a type error.
82 %************************************************************************
84 %* tcImportDecl is the key function for "faulting in" *
87 %************************************************************************
89 The main idea is this. We are chugging along type-checking source code, and
90 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
91 it in the EPS type envt. So it
93 2 gets the decl for GHC.Base.map
94 3 typechecks it via tcIfaceDecl
95 4 and adds it to the type env in the EPS
97 Note that DURING STEP 4, we may find that map's type mentions a type
100 Notice that for imported things we read the current version from the EPS
101 mutable variable. This is important in situations like
103 where the code that e1 expands to might import some defns that
104 also turn out to be needed by the code that e2 expands to.
107 tcImportDecl :: Name -> TcM TyThing
108 -- Entry point for *source-code* uses of importDecl
110 | Just thing <- wiredInNameTyThing_maybe name
111 = do { initIfaceTcRn (loadWiredInHomeIface name)
112 -- See Note [Loading instances] in LoadIface
115 = do { traceIf (text "tcImportDecl" <+> ppr name)
116 ; mb_thing <- initIfaceTcRn (importDecl name)
118 Succeeded thing -> return thing
119 Failed err -> failWithTc err }
121 checkWiredInTyCon :: TyCon -> TcM ()
122 -- Ensure that the home module of the TyCon (and hence its instances)
123 -- are loaded. See See Note [Loading instances] in LoadIface
124 -- It might not be a wired-in tycon (see the calls in TcUnify),
125 -- in which case this is a no-op.
127 | not (isWiredInName tc_name)
130 = do { mod <- getModule
131 ; ASSERT( isExternalName tc_name )
132 unless (mod == nameModule tc_name)
133 (initIfaceTcRn (loadWiredInHomeIface tc_name))
134 -- Don't look for (non-existent) Float.hi when
135 -- compiling Float.lhs, which mentions Float of course
136 -- A bit yukky to call initIfaceTcRn here
139 tc_name = tyConName tc
141 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
142 -- Get the TyThing for this Name from an interface file
143 -- It's not a wired-in thing -- the caller caught that
145 = ASSERT( not (isWiredInName name) )
148 -- Load the interface, which should populate the PTE
149 ; mb_iface <- ASSERT2( isExternalName name, ppr name )
150 loadInterface nd_doc (nameModule name) ImportBySystem
152 Failed err_msg -> return (Failed err_msg) ;
155 -- Now look it up again; this time we should find it
157 ; case lookupTypeEnv (eps_PTE eps) name of
158 Just thing -> return (Succeeded thing)
159 Nothing -> return (Failed not_found_msg)
162 nd_doc = ptext (sLit "Need decl for") <+> ppr name
163 not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
164 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
165 2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
166 ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
169 %************************************************************************
171 Type-checking a complete interface
173 %************************************************************************
175 Suppose we discover we don't need to recompile. Then we must type
176 check the old interface file. This is a bit different to the
177 incremental type checking we do as we suck in interface files. Instead
178 we do things similarly as when we are typechecking source decls: we
179 bring into scope the type envt for the interface all at once, using a
180 knot. Remember, the decls aren't necessarily in dependency order --
181 and even if they were, the type decls might be mutually recursive.
184 typecheckIface :: ModIface -- Get the decls from here
185 -> TcRnIf gbl lcl ModDetails
187 = initIfaceTc iface $ \ tc_env_var -> do
188 -- The tc_env_var is freshly allocated, private to
189 -- type-checking this particular interface
190 { -- Get the right set of decls and rules. If we are compiling without -O
191 -- we discard pragmas before typechecking, so that we don't "see"
192 -- information that we shouldn't. From a versioning point of view
193 -- It's not actually *wrong* to do so, but in fact GHCi is unable
194 -- to handle unboxed tuples, so it must not see unfoldings.
195 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
197 -- Typecheck the decls. This is done lazily, so that the knot-tying
198 -- within this single module work out right. In the If monad there is
199 -- no global envt for the current interface; instead, the knot is tied
200 -- through the if_rec_types field of IfGblEnv
201 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
202 ; let type_env = mkNameEnv names_w_things
203 ; writeMutVar tc_env_var type_env
205 -- Now do those rules, instances and annotations
206 ; insts <- mapM tcIfaceInst (mi_insts iface)
207 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
208 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
209 ; anns <- tcIfaceAnnotations (mi_anns iface)
211 -- Vectorisation information
212 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
216 ; exports <- ifaceExportNames (mi_exports iface)
219 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
220 text "Type envt:" <+> ppr type_env])
221 ; return $ ModDetails { md_types = type_env
223 , md_fam_insts = fam_insts
226 , md_vect_info = vect_info
227 , md_exports = exports
233 %************************************************************************
235 Type and class declarations
237 %************************************************************************
240 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
241 -- Load the hi-boot iface for the module being compiled,
242 -- if it indeed exists in the transitive closure of imports
243 -- Return the ModDetails, empty if no hi-boot iface
244 tcHiBootIface hsc_src mod
245 | isHsBoot hsc_src -- Already compiling a hs-boot file
246 = return emptyModDetails
248 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
251 ; if not (isOneShot mode)
252 -- In --make and interactive mode, if this module has an hs-boot file
253 -- we'll have compiled it already, and it'll be in the HPT
255 -- We check wheher the interface is a *boot* interface.
256 -- It can happen (when using GHC from Visual Studio) that we
257 -- compile a module in TypecheckOnly mode, with a stable,
258 -- fully-populated HPT. In that case the boot interface isn't there
259 -- (it's been replaced by the mother module) so we can't check it.
260 -- And that's fine, because if M's ModInfo is in the HPT, then
261 -- it's been compiled once, and we don't need to check the boot iface
262 then do { hpt <- getHpt
263 ; case lookupUFM hpt (moduleName mod) of
264 Just info | mi_boot (hm_iface info)
265 -> return (hm_details info)
266 _ -> return emptyModDetails }
269 -- OK, so we're in one-shot mode.
270 -- In that case, we're read all the direct imports by now,
271 -- so eps_is_boot will record if any of our imports mention us by
272 -- way of hi-boot file
274 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
275 Nothing -> return emptyModDetails ; -- The typical case
277 Just (_, False) -> failWithTc moduleLoop ;
278 -- Someone below us imported us!
279 -- This is a loop with no hi-boot in the way
281 Just (_mod, True) -> -- There's a hi-boot interface below us
283 do { read_result <- findAndReadIface
287 ; case read_result of
288 Failed err -> failWithTc (elaborate err)
289 Succeeded (iface, _path) -> typecheckIface iface
292 need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
293 <+> ptext (sLit "to compare against the Real Thing")
295 moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod)
296 <+> ptext (sLit "depends on itself")
298 elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+>
299 quotes (ppr mod) <> colon) 4 err
303 %************************************************************************
305 Type and class declarations
307 %************************************************************************
309 When typechecking a data type decl, we *lazily* (via forkM) typecheck
310 the constructor argument types. This is in the hope that we may never
311 poke on those argument types, and hence may never need to load the
312 interface files for types mentioned in the arg types.
315 data Foo.S = MkS Baz.T
316 Mabye we can get away without even loading the interface for Baz!
318 This is not just a performance thing. Suppose we have
319 data Foo.S = MkS Baz.T
320 data Baz.T = MkT Foo.S
321 (in different interface files, of course).
322 Now, first we load and typecheck Foo.S, and add it to the type envt.
323 If we do explore MkS's argument, we'll load and typecheck Baz.T.
324 If we explore MkT's argument we'll find Foo.S already in the envt.
326 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
327 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
328 which isn't done yet.
330 All very cunning. However, there is a rather subtle gotcha which bit
331 me when developing this stuff. When we typecheck the decl for S, we
332 extend the type envt with S, MkS, and all its implicit Ids. Suppose
333 (a bug, but it happened) that the list of implicit Ids depended in
334 turn on the constructor arg types. Then the following sequence of
336 * we build a thunk <t> for the constructor arg tys
337 * we build a thunk for the extended type environment (depends on <t>)
338 * we write the extended type envt into the global EPS mutvar
340 Now we look something up in the type envt
342 * which reads the global type envt out of the global EPS mutvar
343 * but that depends in turn on <t>
345 It's subtle, because, it'd work fine if we typechecked the constructor args
346 eagerly -- they don't need the extended type envt. They just get the extended
347 type envt by accident, because they look at it later.
349 What this means is that the implicitTyThings MUST NOT DEPEND on any of
354 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
358 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
359 = do { name <- lookupIfaceTop occ_name
360 ; ty <- tcIfaceType iface_type
361 ; info <- tcIdInfo ignore_prags name ty info
362 ; return (AnId (mkVanillaGlobalWithInfo name ty info)) }
364 tcIfaceDecl _ (IfaceData {ifName = occ_name,
366 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
369 ifGeneric = want_generic,
370 ifFamInst = mb_family })
371 = do { tc_name <- lookupIfaceTop occ_name
372 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
374 { tycon <- fixM ( \ tycon -> do
375 { stupid_theta <- tcIfaceCtxt ctxt
378 Nothing -> return Nothing
380 do { famTyCon <- tcIfaceTyCon fam
381 ; insttys <- mapM tcIfaceType tys
382 ; return $ Just (famTyCon, insttys)
384 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
385 ; buildAlgTyCon tc_name tyvars stupid_theta
386 cons is_rec want_generic gadt_syn famInst
388 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
389 ; return (ATyCon tycon)
392 tcIfaceDecl _ (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
393 ifSynRhs = mb_rhs_ty,
394 ifSynKind = kind, ifFamInst = mb_family})
395 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
396 { tc_name <- lookupIfaceTop occ_name
397 ; rhs_kind <- tcIfaceType kind -- Note [Synonym kind loop]
398 ; ~(rhs, fam) <- forkM (mk_doc tc_name) $
399 do { rhs <- tc_syn_rhs rhs_kind mb_rhs_ty
400 ; fam <- tc_syn_fam mb_family
401 ; return (rhs, fam) }
402 ; tycon <- buildSynTyCon tc_name tyvars rhs rhs_kind fam
403 ; return $ ATyCon tycon
406 mk_doc n = ptext (sLit "Type syonym") <+> ppr n
407 tc_syn_rhs kind Nothing = return (OpenSynTyCon kind Nothing)
408 tc_syn_rhs _ (Just ty) = do { rhs_ty <- tcIfaceType ty
409 ; return (SynonymTyCon rhs_ty) }
412 tc_syn_fam (Just (fam, tys))
413 = do { famTyCon <- tcIfaceTyCon fam
414 ; insttys <- mapM tcIfaceType tys
415 ; return $ Just (famTyCon, insttys) }
417 tcIfaceDecl ignore_prags
418 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
419 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
420 ifATs = rdr_ats, ifSigs = rdr_sigs,
422 -- ToDo: in hs-boot files we should really treat abstract classes specially,
423 -- as we do abstract tycons
424 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
425 { cls_name <- lookupIfaceTop occ_name
426 ; ctxt <- tcIfaceCtxt rdr_ctxt
427 ; sigs <- mapM tc_sig rdr_sigs
428 ; fds <- mapM tc_fd rdr_fds
429 ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
430 ; let ats = map (setAssocFamilyPermutation tyvars) ats'
431 ; cls <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
432 ; return (AClass cls) }
434 tc_sig (IfaceClassOp occ dm rdr_ty)
435 = do { op_name <- lookupIfaceTop occ
436 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
437 -- Must be done lazily for just the same reason as the
438 -- type of a data con; to avoid sucking in types that
439 -- it mentions unless it's necessray to do so
440 ; return (op_name, dm, op_ty) }
442 mk_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
444 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
445 ; tvs2' <- mapM tcIfaceTyVar tvs2
446 ; return (tvs1', tvs2') }
448 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
449 = do { name <- lookupIfaceTop rdr_name
450 ; return (ATyCon (mkForeignTyCon name ext_name
453 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
454 tcIfaceDataCons tycon_name tycon _ if_cons
456 IfAbstractTyCon -> return mkAbstractTyConRhs
457 IfOpenDataTyCon -> return mkOpenDataTyConRhs
458 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
459 ; return (mkDataTyConRhs data_cons) }
460 IfNewTyCon con -> do { data_con <- tc_con_decl con
461 ; mkNewTyConRhs tycon_name tycon data_con }
463 tc_con_decl (IfCon { ifConInfix = is_infix,
464 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
465 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
466 ifConArgTys = args, ifConFields = field_lbls,
467 ifConStricts = stricts})
468 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
469 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
470 { name <- lookupIfaceTop occ
471 ; eq_spec <- tcIfaceEqSpec spec
472 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
473 -- At one stage I thought that this context checking *had*
474 -- to be lazy, because of possible mutual recursion between the
475 -- type and the classe:
477 -- class Real a where { toRat :: a -> Ratio Integer }
478 -- data (Real a) => Ratio a = ...
479 -- But now I think that the laziness in checking class ops breaks
480 -- the loop, so no laziness needed
482 -- Read the argument types, but lazily to avoid faulting in
483 -- the component types unless they are really needed
484 ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
485 ; lbl_names <- mapM lookupIfaceTop field_lbls
487 -- Remember, tycon is the representation tycon
488 ; let orig_res_ty = mkFamilyTyConApp tycon
489 (substTyVars (mkTopTvSubst eq_spec) univ_tyvars)
491 ; buildDataCon name is_infix {- Not infix -}
493 univ_tyvars ex_tyvars
495 arg_tys orig_res_ty tycon
497 mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
499 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
503 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
504 ; ty <- tcIfaceType if_ty
508 Note [Synonym kind loop]
509 ~~~~~~~~~~~~~~~~~~~~~~~~
510 Notice that we eagerly grab the *kind* from the interface file, but
511 build a forkM thunk for the *rhs* (and family stuff). To see why,
512 consider this (Trac #2412)
514 M.hs: module M where { import X; data T = MkT S }
515 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
516 M.hs-boot: module M where { data T }
518 When kind-checking M.hs we need S's kind. But we do not want to
519 find S's kind from (typeKind S-rhs), because we don't want to look at
520 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
521 be defined, and we must not do that until we've finished with M.T.
523 Solution: record S's kind in the interface file; now we can safely
526 %************************************************************************
530 %************************************************************************
533 tcIfaceInst :: IfaceInst -> IfL Instance
534 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
535 ifInstCls = cls, ifInstTys = mb_tcs })
536 = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
537 tcIfaceExtId dfun_occ
538 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
539 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
541 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
542 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
543 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
544 -- { tycon' <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
545 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
546 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
548 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
549 return (mkImportedFamInst fam mb_tcs' tycon')
553 %************************************************************************
557 %************************************************************************
559 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
560 are in the type environment. However, remember that typechecking a Rule may
561 (as a side effect) augment the type envt, and so we may need to iterate the process.
564 tcIfaceRules :: Bool -- True <=> ignore rules
567 tcIfaceRules ignore_prags if_rules
568 | ignore_prags = return []
569 | otherwise = mapM tcIfaceRule if_rules
571 tcIfaceRule :: IfaceRule -> IfL CoreRule
572 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
573 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
574 = do { ~(bndrs', args', rhs') <-
575 -- Typecheck the payload lazily, in the hope it'll never be looked at
576 forkM (ptext (sLit "Rule") <+> ftext name) $
577 bindIfaceBndrs bndrs $ \ bndrs' ->
578 do { args' <- mapM tcIfaceExpr args
579 ; rhs' <- tcIfaceExpr rhs
580 ; return (bndrs', args', rhs') }
581 ; let mb_tcs = map ifTopFreeName args
582 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
583 ru_bndrs = bndrs', ru_args = args',
586 ru_local = False }) } -- An imported RULE is never for a local Id
587 -- or, even if it is (module loop, perhaps)
588 -- we'll just leave it in the non-local set
590 -- This function *must* mirror exactly what Rules.topFreeName does
591 -- We could have stored the ru_rough field in the iface file
592 -- but that would be redundant, I think.
593 -- The only wrinkle is that we must not be deceived by
594 -- type syononyms at the top of a type arg. Since
595 -- we can't tell at this point, we are careful not
596 -- to write them out in coreRuleToIfaceRule
597 ifTopFreeName :: IfaceExpr -> Maybe Name
598 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
599 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
600 ifTopFreeName (IfaceExt n) = Just n
601 ifTopFreeName _ = Nothing
605 %************************************************************************
609 %************************************************************************
612 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
613 tcIfaceAnnotations = mapM tcIfaceAnnotation
615 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
616 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
617 target' <- tcIfaceAnnTarget target
618 return $ Annotation {
619 ann_target = target',
620 ann_value = serialized
623 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
624 tcIfaceAnnTarget (NamedTarget occ) = do
625 name <- lookupIfaceTop occ
626 return $ NamedTarget name
627 tcIfaceAnnTarget (ModuleTarget mod) = do
628 return $ ModuleTarget mod
633 %************************************************************************
635 Vectorisation information
637 %************************************************************************
640 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
641 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
642 { ifaceVectInfoVar = vars
643 , ifaceVectInfoTyCon = tycons
644 , ifaceVectInfoTyConReuse = tyconsReuse
646 = do { vVars <- mapM vectVarMapping vars
647 ; tyConRes1 <- mapM vectTyConMapping tycons
648 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
649 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
651 { vectInfoVar = mkVarEnv vVars
652 , vectInfoTyCon = mkNameEnv vTyCons
653 , vectInfoDataCon = mkNameEnv (concat vDataCons)
654 , vectInfoPADFun = mkNameEnv vPAs
655 , vectInfoIso = mkNameEnv vIsos
660 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
661 ; let { var = lookupVar name
662 ; vVar = lookupVar vName
664 ; return (var, (var, vVar))
666 vectTyConMapping name
667 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
668 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
669 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
670 ; let { tycon = lookupTyCon name
671 ; vTycon = lookupTyCon vName
672 ; paTycon = lookupVar paName
673 ; isoTycon = lookupVar isoName
675 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
676 ; return ((name, (tycon, vTycon)), -- (T, T_v)
677 vDataCons, -- list of (Ci, Ci_v)
678 (vName, (vTycon, paTycon)), -- (T_v, paT)
679 (name, (tycon, isoTycon))) -- (T, isoT)
681 vectTyConReuseMapping name
682 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
683 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
684 ; let { tycon = lookupTyCon name
685 ; paTycon = lookupVar paName
686 ; isoTycon = lookupVar isoName
687 ; vDataCons = [ (dataConName dc, (dc, dc))
688 | dc <- tyConDataCons tycon]
690 ; return ((name, (tycon, tycon)), -- (T, T)
691 vDataCons, -- list of (Ci, Ci)
692 (name, (tycon, paTycon)), -- (T, paT)
693 (name, (tycon, isoTycon))) -- (T, isoT)
695 vectDataConMapping datacon
696 = do { let name = dataConName datacon
697 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
698 ; let vDataCon = lookupDataCon vName
699 ; return (name, (datacon, vDataCon))
702 lookupVar name = case lookupTypeEnv typeEnv name of
703 Just (AnId var) -> var
705 panic "TcIface.tcIfaceVectInfo: not an id"
707 panic "TcIface.tcIfaceVectInfo: unknown name"
708 lookupTyCon name = case lookupTypeEnv typeEnv name of
709 Just (ATyCon tc) -> tc
711 panic "TcIface.tcIfaceVectInfo: not a tycon"
713 panic "TcIface.tcIfaceVectInfo: unknown name"
714 lookupDataCon name = case lookupTypeEnv typeEnv name of
715 Just (ADataCon dc) -> dc
717 panic "TcIface.tcIfaceVectInfo: not a datacon"
719 panic "TcIface.tcIfaceVectInfo: unknown name"
722 %************************************************************************
726 %************************************************************************
729 tcIfaceType :: IfaceType -> IfL Type
730 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
731 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
732 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
733 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
734 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
735 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
737 tcIfaceTypes :: [IfaceType] -> IfL [Type]
738 tcIfaceTypes tys = mapM tcIfaceType tys
740 -----------------------------------------
741 tcIfacePredType :: IfacePredType -> IfL PredType
742 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
743 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
744 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
746 -----------------------------------------
747 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
748 tcIfaceCtxt sts = mapM tcIfacePredType sts
752 %************************************************************************
756 %************************************************************************
759 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
760 tcIfaceExpr (IfaceType ty)
761 = Type <$> tcIfaceType ty
763 tcIfaceExpr (IfaceLcl name)
764 = Var <$> tcIfaceLclId name
766 tcIfaceExpr (IfaceTick modName tickNo)
767 = Var <$> tcIfaceTick modName tickNo
769 tcIfaceExpr (IfaceExt gbl)
770 = Var <$> tcIfaceExtId gbl
772 tcIfaceExpr (IfaceLit lit)
775 tcIfaceExpr (IfaceFCall cc ty) = do
776 ty' <- tcIfaceType ty
778 return (Var (mkFCallId u cc ty'))
780 tcIfaceExpr (IfaceTuple boxity args) = do
781 args' <- mapM tcIfaceExpr args
782 -- Put the missing type arguments back in
783 let con_args = map (Type . exprType) args' ++ args'
784 return (mkApps (Var con_id) con_args)
787 con_id = dataConWorkId (tupleCon boxity arity)
790 tcIfaceExpr (IfaceLam bndr body)
791 = bindIfaceBndr bndr $ \bndr' ->
792 Lam bndr' <$> tcIfaceExpr body
794 tcIfaceExpr (IfaceApp fun arg)
795 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
797 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
798 scrut' <- tcIfaceExpr scrut
799 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
801 scrut_ty = exprType scrut'
802 case_bndr' = mkLocalId case_bndr_name scrut_ty
803 tc_app = splitTyConApp scrut_ty
804 -- NB: Won't always succeed (polymoprhic case)
805 -- but won't be demanded in those cases
806 -- NB: not tcSplitTyConApp; we are looking at Core here
807 -- look through non-rec newtypes to find the tycon that
808 -- corresponds to the datacon in this case alternative
810 extendIfaceIdEnv [case_bndr'] $ do
811 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
812 ty' <- tcIfaceType ty
813 return (Case scrut' case_bndr' ty' alts')
815 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
816 rhs' <- tcIfaceExpr rhs
817 id <- tcIfaceLetBndr bndr
818 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
819 return (Let (NonRec id rhs') body')
821 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
822 ids <- mapM tcIfaceLetBndr bndrs
823 extendIfaceIdEnv ids $ do
824 rhss' <- mapM tcIfaceExpr rhss
825 body' <- tcIfaceExpr body
826 return (Let (Rec (ids `zip` rhss')) body')
828 (bndrs, rhss) = unzip pairs
830 tcIfaceExpr (IfaceCast expr co) = do
831 expr' <- tcIfaceExpr expr
832 co' <- tcIfaceType co
833 return (Cast expr' co')
835 tcIfaceExpr (IfaceNote note expr) = do
836 expr' <- tcIfaceExpr expr
838 IfaceInlineMe -> return (Note InlineMe expr')
839 IfaceSCC cc -> return (Note (SCC cc) expr')
840 IfaceCoreNote n -> return (Note (CoreNote n) expr')
842 -------------------------
843 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
844 -> (IfaceConAlt, [FastString], IfaceExpr)
845 -> IfL (AltCon, [TyVar], CoreExpr)
846 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
847 = ASSERT( null names ) do
848 rhs' <- tcIfaceExpr rhs
849 return (DEFAULT, [], rhs')
851 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
852 = ASSERT( null names ) do
853 rhs' <- tcIfaceExpr rhs
854 return (LitAlt lit, [], rhs')
856 -- A case alternative is made quite a bit more complicated
857 -- by the fact that we omit type annotations because we can
858 -- work them out. True enough, but its not that easy!
859 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
860 = do { con <- tcIfaceDataCon data_occ
861 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
862 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
863 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
865 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
866 = ASSERT( isTupleTyCon tycon )
867 do { let [data_con] = tyConDataCons tycon
868 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
870 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
871 -> IfL (AltCon, [TyVar], CoreExpr)
872 tcIfaceDataAlt con inst_tys arg_strs rhs
873 = do { us <- newUniqueSupply
874 ; let uniqs = uniqsFromSupply us
875 ; let (ex_tvs, co_tvs, arg_ids)
876 = dataConRepFSInstPat arg_strs uniqs con inst_tys
877 all_tvs = ex_tvs ++ co_tvs
879 ; rhs' <- extendIfaceTyVarEnv all_tvs $
880 extendIfaceIdEnv arg_ids $
882 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
887 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
888 tcExtCoreBindings [] = return []
889 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
891 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
892 do_one (IfaceNonRec bndr rhs) thing_inside
893 = do { rhs' <- tcIfaceExpr rhs
894 ; bndr' <- newExtCoreBndr bndr
895 ; extendIfaceIdEnv [bndr'] $ do
896 { core_binds <- thing_inside
897 ; return (NonRec bndr' rhs' : core_binds) }}
899 do_one (IfaceRec pairs) thing_inside
900 = do { bndrs' <- mapM newExtCoreBndr bndrs
901 ; extendIfaceIdEnv bndrs' $ do
902 { rhss' <- mapM tcIfaceExpr rhss
903 ; core_binds <- thing_inside
904 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
906 (bndrs,rhss) = unzip pairs
910 %************************************************************************
914 %************************************************************************
917 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
918 tcIdInfo ignore_prags name ty info
919 | ignore_prags = return vanillaIdInfo
920 | otherwise = case info of
921 NoInfo -> return vanillaIdInfo
922 HasInfo info -> foldlM tcPrag init_info info
924 -- Set the CgInfo to something sensible but uninformative before
925 -- we start; default assumption is that it has CAFs
926 init_info = vanillaIdInfo
928 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
929 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
930 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
931 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
933 -- The next two are lazy, so they don't transitively suck stuff in
934 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
935 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
936 tcPrag info (HsUnfold expr) = do
937 maybe_expr' <- tcPragExpr name expr
939 -- maybe_expr' doesn't get looked at if the unfolding
940 -- is never inspected; so the typecheck doesn't even happen
941 unfold_info = case maybe_expr' of
942 Nothing -> noUnfolding
943 Just expr' -> mkTopUnfolding expr'
944 return (info `setUnfoldingInfoLazily` unfold_info)
948 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
949 tcWorkerInfo ty info wkr arity
950 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
952 -- We return without testing maybe_wkr_id, but as soon as info is
953 -- looked at we will test it. That's ok, because its outside the
954 -- knot; and there seems no big reason to further defer the
955 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
956 -- over the unfolding until it's actually used does seem worth while.)
957 ; us <- newUniqueSupply
959 ; return (case mb_wkr_id of
961 Just wkr_id -> add_wkr_info us wkr_id info) }
963 doc = text "Worker for" <+> ppr wkr
964 add_wkr_info us wkr_id info
965 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
966 `setWorkerInfo` HasWorker wkr_id arity
968 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
970 -- We are relying here on strictness info always appearing
971 -- before worker info, fingers crossed ....
972 strict_sig = case newStrictnessInfo info of
974 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
977 For unfoldings we try to do the job lazily, so that we never type check
978 an unfolding that isn't going to be looked at.
981 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
983 = forkM_maybe doc $ do
984 core_expr' <- tcIfaceExpr expr
986 -- Check for type consistency in the unfolding
987 ifOptM Opt_DoCoreLinting $ do
988 in_scope <- get_in_scope_ids
989 case lintUnfolding noSrcLoc in_scope core_expr' of
991 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
995 doc = text "Unfolding of" <+> ppr name
996 get_in_scope_ids -- Urgh; but just for linting
998 do { env <- getGblEnv
999 ; case if_rec_types env of {
1000 Nothing -> return [] ;
1001 Just (_, get_env) -> do
1002 { type_env <- get_env
1003 ; return (typeEnvIds type_env) }}}
1008 %************************************************************************
1010 Getting from Names to TyThings
1012 %************************************************************************
1015 tcIfaceGlobal :: Name -> IfL TyThing
1017 | Just thing <- wiredInNameTyThing_maybe name
1018 -- Wired-in things include TyCons, DataCons, and Ids
1019 = do { ifCheckWiredInThing name; return thing }
1021 = do { env <- getGblEnv
1022 ; case if_rec_types env of { -- Note [Tying the knot]
1023 Just (mod, get_type_env)
1024 | nameIsLocalOrFrom mod name
1025 -> do -- It's defined in the module being compiled
1026 { type_env <- setLclEnv () get_type_env -- yuk
1027 ; case lookupNameEnv type_env name of
1028 Just thing -> return thing
1029 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
1030 (ppr name $$ ppr type_env) }
1034 { hsc_env <- getTopEnv
1035 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1036 ; case mb_thing of {
1037 Just thing -> return thing ;
1040 { mb_thing <- importDecl name -- It's imported; go get it
1042 Failed err -> failIfM err
1043 Succeeded thing -> return thing
1046 -- Note [Tying the knot]
1047 -- ~~~~~~~~~~~~~~~~~~~~~
1048 -- The if_rec_types field is used in two situations:
1050 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1051 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1052 -- after we've built M's type envt.
1054 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1055 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1056 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1058 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1059 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1060 -- emasculated form (e.g. lacking data constructors).
1062 ifCheckWiredInThing :: Name -> IfL ()
1063 -- Even though we are in an interface file, we want to make
1064 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1065 -- Ditto want to ensure that RULES are loaded too
1066 -- See Note [Loading instances] in LoadIface
1067 ifCheckWiredInThing name
1068 = do { mod <- getIfModule
1069 -- Check whether we are typechecking the interface for this
1070 -- very module. E.g when compiling the base library in --make mode
1071 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1072 -- the HPT, so without the test we'll demand-load it into the PIT!
1073 -- C.f. the same test in checkWiredInTyCon above
1074 ; ASSERT2( isExternalName name, ppr name )
1075 unless (mod == nameModule name)
1076 (loadWiredInHomeIface name) }
1078 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1079 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1080 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1081 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1082 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1083 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1084 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1085 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1086 ; return (check_tc (tyThingTyCon thing)) }
1089 | debugIsOn = case toIfaceTyCon tc of
1091 _ -> pprTrace "check_tc" (ppr tc) tc
1093 -- we should be okay just returning Kind constructors without extra loading
1094 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1095 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1096 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1097 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1098 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1100 -- Even though we are in an interface file, we want to make
1101 -- sure the instances and RULES of this tycon are loaded
1102 -- Imagine: f :: Double -> Double
1103 tcWiredInTyCon :: TyCon -> IfL TyCon
1104 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1107 tcIfaceClass :: Name -> IfL Class
1108 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1109 ; return (tyThingClass thing) }
1111 tcIfaceDataCon :: Name -> IfL DataCon
1112 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1114 ADataCon dc -> return dc
1115 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1117 tcIfaceExtId :: Name -> IfL Id
1118 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1120 AnId id -> return id
1121 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1124 %************************************************************************
1128 %************************************************************************
1131 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1132 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1133 = do { name <- newIfaceName (mkVarOccFS fs)
1134 ; ty' <- tcIfaceType ty
1135 ; let id = mkLocalId name ty'
1136 ; extendIfaceIdEnv [id] (thing_inside id) }
1137 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1138 = bindIfaceTyVar bndr thing_inside
1140 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1141 bindIfaceBndrs [] thing_inside = thing_inside []
1142 bindIfaceBndrs (b:bs) thing_inside
1143 = bindIfaceBndr b $ \ b' ->
1144 bindIfaceBndrs bs $ \ bs' ->
1145 thing_inside (b':bs')
1147 -----------------------
1148 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1149 tcIfaceLetBndr (IfLetBndr fs ty info)
1150 = do { name <- newIfaceName (mkVarOccFS fs)
1151 ; ty' <- tcIfaceType ty
1153 NoInfo -> return (mkLocalId name ty')
1154 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1156 -- Similar to tcIdInfo, but much simpler
1157 tc_info [] = vanillaIdInfo
1158 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1159 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1160 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1161 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1162 (ppr other) (tc_info i)
1164 -----------------------
1165 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1166 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1167 = do { mod <- getIfModule
1168 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1169 ; ty' <- tcIfaceType ty
1170 ; return (mkLocalId name ty') }
1172 -----------------------
1173 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1174 bindIfaceTyVar (occ,kind) thing_inside
1175 = do { name <- newIfaceName (mkTyVarOccFS occ)
1176 ; tyvar <- mk_iface_tyvar name kind
1177 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1179 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1180 bindIfaceTyVars bndrs thing_inside
1181 = do { names <- newIfaceNames (map mkTyVarOccFS occs)
1182 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1183 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1185 (occs,kinds) = unzip bndrs
1187 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1188 mk_iface_tyvar name ifKind
1189 = do { kind <- tcIfaceType ifKind
1190 ; if isCoercionKind kind then
1191 return (Var.mkCoVar name kind)
1193 return (Var.mkTyVar name kind) }