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"
65 An IfaceDecl is populated with RdrNames, and these are not renamed to
66 Names before typechecking, because there should be no scope errors etc.
68 -- For (b) consider: f = $(...h....)
69 -- where h is imported, and calls f via an hi-boot file.
70 -- This is bad! But it is not seen as a staging error, because h
71 -- is indeed imported. We don't want the type-checker to black-hole
72 -- when simplifying and compiling the splice!
74 -- Simple solution: discard any unfolding that mentions a variable
75 -- bound in this module (and hence not yet processed).
76 -- The discarding happens when forkM finds a type error.
78 %************************************************************************
80 %* tcImportDecl is the key function for "faulting in" *
83 %************************************************************************
85 The main idea is this. We are chugging along type-checking source code, and
86 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
87 it in the EPS type envt. So it
89 2 gets the decl for GHC.Base.map
90 3 typechecks it via tcIfaceDecl
91 4 and adds it to the type env in the EPS
93 Note that DURING STEP 4, we may find that map's type mentions a type
96 Notice that for imported things we read the current version from the EPS
97 mutable variable. This is important in situations like
99 where the code that e1 expands to might import some defns that
100 also turn out to be needed by the code that e2 expands to.
103 tcImportDecl :: Name -> TcM TyThing
104 -- Entry point for *source-code* uses of importDecl
106 | Just thing <- wiredInNameTyThing_maybe name
107 = do { initIfaceTcRn (loadWiredInHomeIface name)
108 -- See Note [Loading instances] in LoadIface
111 = do { traceIf (text "tcImportDecl" <+> ppr name)
112 ; mb_thing <- initIfaceTcRn (importDecl name)
114 Succeeded thing -> return thing
115 Failed err -> failWithTc err }
117 checkWiredInTyCon :: TyCon -> TcM ()
118 -- Ensure that the home module of the TyCon (and hence its instances)
119 -- are loaded. See See Note [Loading instances] in LoadIface
120 -- It might not be a wired-in tycon (see the calls in TcUnify),
121 -- in which case this is a no-op.
123 | not (isWiredInName tc_name)
126 = do { mod <- getModule
127 ; unless (mod == nameModule tc_name)
128 (initIfaceTcRn (loadWiredInHomeIface tc_name))
129 -- Don't look for (non-existent) Float.hi when
130 -- compiling Float.lhs, which mentions Float of course
131 -- A bit yukky to call initIfaceTcRn here
134 tc_name = tyConName tc
136 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
137 -- Get the TyThing for this Name from an interface file
138 -- It's not a wired-in thing -- the caller caught that
140 = ASSERT( not (isWiredInName name) )
143 -- Load the interface, which should populate the PTE
144 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
146 Failed err_msg -> return (Failed err_msg) ;
147 Succeeded iface -> do
149 -- Now look it up again; this time we should find it
151 ; case lookupTypeEnv (eps_PTE eps) name of
152 Just thing -> return (Succeeded thing)
153 Nothing -> return (Failed not_found_msg)
156 nd_doc = ptext SLIT("Need decl for") <+> ppr name
157 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
158 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
159 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
160 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
163 %************************************************************************
165 Type-checking a complete interface
167 %************************************************************************
169 Suppose we discover we don't need to recompile. Then we must type
170 check the old interface file. This is a bit different to the
171 incremental type checking we do as we suck in interface files. Instead
172 we do things similarly as when we are typechecking source decls: we
173 bring into scope the type envt for the interface all at once, using a
174 knot. Remember, the decls aren't necessarily in dependency order --
175 and even if they were, the type decls might be mutually recursive.
178 typecheckIface :: ModIface -- Get the decls from here
179 -> TcRnIf gbl lcl ModDetails
181 = initIfaceTc iface $ \ tc_env_var -> do
182 -- The tc_env_var is freshly allocated, private to
183 -- type-checking this particular interface
184 { -- Get the right set of decls and rules. If we are compiling without -O
185 -- we discard pragmas before typechecking, so that we don't "see"
186 -- information that we shouldn't. From a versioning point of view
187 -- It's not actually *wrong* to do so, but in fact GHCi is unable
188 -- to handle unboxed tuples, so it must not see unfoldings.
189 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
191 -- Typecheck the decls. This is done lazily, so that the knot-tying
192 -- within this single module work out right. In the If monad there is
193 -- no global envt for the current interface; instead, the knot is tied
194 -- through the if_rec_types field of IfGblEnv
195 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
196 ; let type_env = mkNameEnv names_w_things
197 ; writeMutVar tc_env_var type_env
199 -- Now do those rules and instances
200 ; insts <- mapM tcIfaceInst (mi_insts iface)
201 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
202 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
204 -- Vectorisation information
205 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
209 ; exports <- ifaceExportNames (mi_exports iface)
212 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
213 text "Type envt:" <+> ppr type_env])
214 ; return $ ModDetails { md_types = type_env
216 , md_fam_insts = fam_insts
218 , md_vect_info = vect_info
219 , md_exports = exports
220 , md_modBreaks = emptyModBreaks
226 %************************************************************************
228 Type and class declarations
230 %************************************************************************
233 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
234 -- Load the hi-boot iface for the module being compiled,
235 -- if it indeed exists in the transitive closure of imports
236 -- Return the ModDetails, empty if no hi-boot iface
237 tcHiBootIface hsc_src mod
238 | isHsBoot hsc_src -- Already compiling a hs-boot file
239 = return emptyModDetails
241 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
244 ; if not (isOneShot mode)
245 -- In --make and interactive mode, if this module has an hs-boot file
246 -- we'll have compiled it already, and it'll be in the HPT
248 -- We check wheher the interface is a *boot* interface.
249 -- It can happen (when using GHC from Visual Studio) that we
250 -- compile a module in TypecheckOnly mode, with a stable,
251 -- fully-populated HPT. In that case the boot interface isn't there
252 -- (it's been replaced by the mother module) so we can't check it.
253 -- And that's fine, because if M's ModInfo is in the HPT, then
254 -- it's been compiled once, and we don't need to check the boot iface
255 then do { hpt <- getHpt
256 ; case lookupUFM hpt (moduleName mod) of
257 Just info | mi_boot (hm_iface info)
258 -> return (hm_details info)
259 other -> return emptyModDetails }
262 -- OK, so we're in one-shot mode.
263 -- In that case, we're read all the direct imports by now,
264 -- so eps_is_boot will record if any of our imports mention us by
265 -- way of hi-boot file
267 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
268 Nothing -> return emptyModDetails ; -- The typical case
270 Just (_, False) -> failWithTc moduleLoop ;
271 -- Someone below us imported us!
272 -- This is a loop with no hi-boot in the way
274 Just (_mod, True) -> -- There's a hi-boot interface below us
276 do { read_result <- findAndReadIface
280 ; case read_result of
281 Failed err -> failWithTc (elaborate err)
282 Succeeded (iface, _path) -> typecheckIface iface
285 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
286 <+> ptext SLIT("to compare against the Real Thing")
288 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
289 <+> ptext SLIT("depends on itself")
291 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
292 quotes (ppr mod) <> colon) 4 err
296 %************************************************************************
298 Type and class declarations
300 %************************************************************************
302 When typechecking a data type decl, we *lazily* (via forkM) typecheck
303 the constructor argument types. This is in the hope that we may never
304 poke on those argument types, and hence may never need to load the
305 interface files for types mentioned in the arg types.
308 data Foo.S = MkS Baz.T
309 Mabye we can get away without even loading the interface for Baz!
311 This is not just a performance thing. Suppose we have
312 data Foo.S = MkS Baz.T
313 data Baz.T = MkT Foo.S
314 (in different interface files, of course).
315 Now, first we load and typecheck Foo.S, and add it to the type envt.
316 If we do explore MkS's argument, we'll load and typecheck Baz.T.
317 If we explore MkT's argument we'll find Foo.S already in the envt.
319 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
320 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
321 which isn't done yet.
323 All very cunning. However, there is a rather subtle gotcha which bit
324 me when developing this stuff. When we typecheck the decl for S, we
325 extend the type envt with S, MkS, and all its implicit Ids. Suppose
326 (a bug, but it happened) that the list of implicit Ids depended in
327 turn on the constructor arg types. Then the following sequence of
329 * we build a thunk <t> for the constructor arg tys
330 * we build a thunk for the extended type environment (depends on <t>)
331 * we write the extended type envt into the global EPS mutvar
333 Now we look something up in the type envt
335 * which reads the global type envt out of the global EPS mutvar
336 * but that depends in turn on <t>
338 It's subtle, because, it'd work fine if we typechecked the constructor args
339 eagerly -- they don't need the extended type envt. They just get the extended
340 type envt by accident, because they look at it later.
342 What this means is that the implicitTyThings MUST NOT DEPEND on any of
347 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
351 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
352 = do { name <- lookupIfaceTop occ_name
353 ; ty <- tcIfaceType iface_type
354 ; info <- tcIdInfo ignore_prags name ty info
355 ; return (AnId (mkVanillaGlobal name ty info)) }
357 tcIfaceDecl ignore_prags
358 (IfaceData {ifName = occ_name,
360 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
363 ifGeneric = want_generic,
364 ifFamInst = mb_family })
365 = do { tc_name <- lookupIfaceTop occ_name
366 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
368 { tycon <- fixM ( \ tycon -> do
369 { stupid_theta <- tcIfaceCtxt ctxt
372 Nothing -> return Nothing
374 do { famTyCon <- tcIfaceTyCon fam
375 ; insttys <- mapM tcIfaceType tys
376 ; return $ Just (famTyCon, insttys)
378 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
379 ; buildAlgTyCon tc_name tyvars stupid_theta
380 cons is_rec want_generic gadt_syn famInst
382 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
383 ; return (ATyCon tycon)
386 tcIfaceDecl ignore_prags
387 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
388 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty,
389 ifFamInst = mb_family})
390 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
391 { tc_name <- lookupIfaceTop occ_name
392 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
393 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
394 else SynonymTyCon rhs_tyki
395 ; famInst <- case mb_family of
396 Nothing -> return Nothing
398 do { famTyCon <- tcIfaceTyCon fam
399 ; insttys <- mapM tcIfaceType tys
400 ; return $ Just (famTyCon, insttys)
402 ; tycon <- buildSynTyCon tc_name tyvars rhs famInst
403 ; return $ ATyCon tycon
406 tcIfaceDecl ignore_prags
407 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
408 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
409 ifATs = rdr_ats, ifSigs = rdr_sigs,
411 -- ToDo: in hs-boot files we should really treat abstract classes specially,
412 -- as we do abstract tycons
413 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
414 { cls_name <- lookupIfaceTop occ_name
415 ; ctxt <- tcIfaceCtxt rdr_ctxt
416 ; sigs <- mappM tc_sig rdr_sigs
417 ; fds <- mappM tc_fd rdr_fds
418 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
419 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
420 ; cls <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
421 ; return (AClass cls) }
423 tc_sig (IfaceClassOp occ dm rdr_ty)
424 = do { op_name <- lookupIfaceTop occ
425 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
426 -- Must be done lazily for just the same reason as the
427 -- type of a data con; to avoid sucking in types that
428 -- it mentions unless it's necessray to do so
429 ; return (op_name, dm, op_ty) }
431 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
433 tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
434 ; tvs2' <- mappM tcIfaceTyVar tvs2
435 ; return (tvs1', tvs2') }
437 -- For each AT argument compute the position of the corresponding class
438 -- parameter in the class head. This will later serve as a permutation
439 -- vector when checking the validity of instance declarations.
440 setTyThingPoss (ATyCon tycon) atTyVars =
441 let classTyVars = map fst tv_bndrs
443 . map ((`elemIndex` classTyVars) . fst)
445 -- There will be no Nothing, as we already passed renaming
447 ATyCon (setTyConArgPoss tycon poss)
448 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
450 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
451 = do { name <- lookupIfaceTop rdr_name
452 ; return (ATyCon (mkForeignTyCon name ext_name
455 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
457 IfAbstractTyCon -> return mkAbstractTyConRhs
458 IfOpenDataTyCon -> return mkOpenDataTyConRhs
459 IfDataTyCon cons -> do { data_cons <- mappM tc_con_decl cons
460 ; return (mkDataTyConRhs data_cons) }
461 IfNewTyCon con -> do { data_con <- tc_con_decl con
462 ; mkNewTyConRhs tycon_name tycon data_con }
464 tc_con_decl (IfCon { ifConInfix = is_infix,
465 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
466 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
467 ifConArgTys = args, ifConFields = field_lbls,
468 ifConStricts = stricts})
469 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
470 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
471 { name <- lookupIfaceTop occ
472 ; eq_spec <- tcIfaceEqSpec spec
473 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
474 -- At one stage I thought that this context checking *had*
475 -- to be lazy, because of possible mutual recursion between the
476 -- type and the classe:
478 -- class Real a where { toRat :: a -> Ratio Integer }
479 -- data (Real a) => Ratio a = ...
480 -- But now I think that the laziness in checking class ops breaks
481 -- the loop, so no laziness needed
483 -- Read the argument types, but lazily to avoid faulting in
484 -- the component types unless they are really needed
485 ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
486 ; lbl_names <- mappM lookupIfaceTop field_lbls
488 ; buildDataCon name is_infix {- Not infix -}
490 univ_tyvars ex_tyvars
494 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
499 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
500 ; ty <- tcIfaceType if_ty
505 %************************************************************************
509 %************************************************************************
512 tcIfaceInst :: IfaceInst -> IfL Instance
513 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
514 ifInstCls = cls, ifInstTys = mb_tcs,
516 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
517 tcIfaceExtId dfun_occ
518 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
519 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
521 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
522 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
523 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
524 -- = do { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
525 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
526 = do { tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
528 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
529 ; return (mkImportedFamInst fam mb_tcs' tycon') }
533 %************************************************************************
537 %************************************************************************
539 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
540 are in the type environment. However, remember that typechecking a Rule may
541 (as a side effect) augment the type envt, and so we may need to iterate the process.
544 tcIfaceRules :: Bool -- True <=> ignore rules
547 tcIfaceRules ignore_prags if_rules
548 | ignore_prags = return []
549 | otherwise = mapM tcIfaceRule if_rules
551 tcIfaceRule :: IfaceRule -> IfL CoreRule
552 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
553 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
555 = do { ~(bndrs', args', rhs') <-
556 -- Typecheck the payload lazily, in the hope it'll never be looked at
557 forkM (ptext SLIT("Rule") <+> ftext name) $
558 bindIfaceBndrs bndrs $ \ bndrs' ->
559 do { args' <- mappM tcIfaceExpr args
560 ; rhs' <- tcIfaceExpr rhs
561 ; return (bndrs', args', rhs') }
562 ; let mb_tcs = map ifTopFreeName args
563 ; returnM (Rule { ru_name = name, ru_fn = fn, ru_act = act,
564 ru_bndrs = bndrs', ru_args = args',
567 ru_local = False }) } -- An imported RULE is never for a local Id
568 -- or, even if it is (module loop, perhaps)
569 -- we'll just leave it in the non-local set
571 -- This function *must* mirror exactly what Rules.topFreeName does
572 -- We could have stored the ru_rough field in the iface file
573 -- but that would be redundant, I think.
574 -- The only wrinkle is that we must not be deceived by
575 -- type syononyms at the top of a type arg. Since
576 -- we can't tell at this point, we are careful not
577 -- to write them out in coreRuleToIfaceRule
578 ifTopFreeName :: IfaceExpr -> Maybe Name
579 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
580 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
581 ifTopFreeName (IfaceExt n) = Just n
582 ifTopFreeName other = Nothing
586 %************************************************************************
588 Vectorisation information
590 %************************************************************************
593 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
594 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
595 { ifaceVectInfoVar = vars
596 , ifaceVectInfoTyCon = tycons
597 , ifaceVectInfoTyConReuse = tyconsReuse
599 = do { vVars <- mapM vectVarMapping vars
600 ; tyConRes1 <- mapM vectTyConMapping tycons
601 ; tyConRes2 <- mapM vectTyConReuseMapping tycons
602 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
604 { vectInfoVar = mkVarEnv vVars
605 , vectInfoTyCon = mkNameEnv vTyCons
606 , vectInfoDataCon = mkNameEnv (concat vDataCons)
607 , vectInfoPADFun = mkNameEnv vPAs
608 , vectInfoIso = mkNameEnv vIsos
613 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
614 ; let { var = lookupVar name
615 ; vVar = lookupVar vName
617 ; return (var, (var, vVar))
619 vectTyConMapping name
620 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
621 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
622 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
623 ; let { tycon = lookupTyCon name
624 ; vTycon = lookupTyCon vName
625 ; paTycon = lookupVar paName
626 ; isoTycon = lookupVar isoName
628 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
629 ; return ((name, (tycon, vTycon)), -- (T, T_v)
630 vDataCons, -- list of (Ci, Ci_v)
631 (vName, (vTycon, paTycon)), -- (T_v, paT)
632 (name, (tycon, isoTycon))) -- (T, isoT)
634 vectTyConReuseMapping name
635 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
636 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
637 ; let { tycon = lookupTyCon name
638 ; paTycon = lookupVar paName
639 ; isoTycon = lookupVar isoName
640 ; vDataCons = [ (dataConName dc, (dc, dc))
641 | dc <- tyConDataCons tycon]
643 ; return ((name, (tycon, tycon)), -- (T, T)
644 vDataCons, -- list of (Ci, Ci)
645 (name, (tycon, paTycon)), -- (T, paT)
646 (name, (tycon, isoTycon))) -- (T, isoT)
648 vectDataConMapping datacon
649 = do { let name = dataConName datacon
650 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
651 ; let vDataCon = lookupDataCon vName
652 ; return (name, (datacon, vDataCon))
655 lookupVar name = case lookupTypeEnv typeEnv name of
656 Just (AnId var) -> var
658 panic "TcIface.tcIfaceVectInfo: not an id"
660 panic "TcIface.tcIfaceVectInfo: unknown name"
661 lookupTyCon name = case lookupTypeEnv typeEnv name of
662 Just (ATyCon tc) -> tc
664 panic "TcIface.tcIfaceVectInfo: not a tycon"
666 panic "TcIface.tcIfaceVectInfo: unknown name"
667 lookupDataCon name = case lookupTypeEnv typeEnv name of
668 Just (ADataCon dc) -> dc
670 panic "TcIface.tcIfaceVectInfo: not a datacon"
672 panic "TcIface.tcIfaceVectInfo: unknown name"
675 %************************************************************************
679 %************************************************************************
682 tcIfaceType :: IfaceType -> IfL Type
683 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
684 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
685 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
686 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
687 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
688 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
690 tcIfaceTypes tys = mapM tcIfaceType tys
692 -----------------------------------------
693 tcIfacePredType :: IfacePredType -> IfL PredType
694 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
695 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
696 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
698 -----------------------------------------
699 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
700 tcIfaceCtxt sts = mappM tcIfacePredType sts
704 %************************************************************************
708 %************************************************************************
711 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
712 tcIfaceExpr (IfaceType ty)
713 = tcIfaceType ty `thenM` \ ty' ->
716 tcIfaceExpr (IfaceLcl name)
717 = tcIfaceLclId name `thenM` \ id ->
720 tcIfaceExpr (IfaceTick modName tickNo)
721 = tcIfaceTick modName tickNo `thenM` \ id ->
724 tcIfaceExpr (IfaceExt gbl)
725 = tcIfaceExtId gbl `thenM` \ id ->
728 tcIfaceExpr (IfaceLit lit)
731 tcIfaceExpr (IfaceFCall cc ty)
732 = tcIfaceType ty `thenM` \ ty' ->
733 newUnique `thenM` \ u ->
734 returnM (Var (mkFCallId u cc ty'))
736 tcIfaceExpr (IfaceTuple boxity args)
737 = mappM tcIfaceExpr args `thenM` \ args' ->
739 -- Put the missing type arguments back in
740 con_args = map (Type . exprType) args' ++ args'
742 returnM (mkApps (Var con_id) con_args)
745 con_id = dataConWorkId (tupleCon boxity arity)
748 tcIfaceExpr (IfaceLam bndr body)
749 = bindIfaceBndr bndr $ \ bndr' ->
750 tcIfaceExpr body `thenM` \ body' ->
751 returnM (Lam bndr' body')
753 tcIfaceExpr (IfaceApp fun arg)
754 = tcIfaceExpr fun `thenM` \ fun' ->
755 tcIfaceExpr arg `thenM` \ arg' ->
756 returnM (App fun' arg')
758 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
759 = tcIfaceExpr scrut `thenM` \ scrut' ->
760 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
762 scrut_ty = exprType scrut'
763 case_bndr' = mkLocalId case_bndr_name scrut_ty
764 tc_app = splitTyConApp scrut_ty
765 -- NB: Won't always succeed (polymoprhic case)
766 -- but won't be demanded in those cases
767 -- NB: not tcSplitTyConApp; we are looking at Core here
768 -- look through non-rec newtypes to find the tycon that
769 -- corresponds to the datacon in this case alternative
771 extendIfaceIdEnv [case_bndr'] $
772 mappM (tcIfaceAlt scrut' tc_app) alts `thenM` \ alts' ->
773 tcIfaceType ty `thenM` \ ty' ->
774 returnM (Case scrut' case_bndr' ty' alts')
776 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
777 = do { rhs' <- tcIfaceExpr rhs
778 ; id <- tcIfaceLetBndr bndr
779 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
780 ; return (Let (NonRec id rhs') body') }
782 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
783 = do { ids <- mapM tcIfaceLetBndr bndrs
784 ; extendIfaceIdEnv ids $ do
785 { rhss' <- mapM tcIfaceExpr rhss
786 ; body' <- tcIfaceExpr body
787 ; return (Let (Rec (ids `zip` rhss')) body') } }
789 (bndrs, rhss) = unzip pairs
791 tcIfaceExpr (IfaceCast expr co) = do
792 expr' <- tcIfaceExpr expr
793 co' <- tcIfaceType co
794 returnM (Cast expr' co')
796 tcIfaceExpr (IfaceNote note expr)
797 = tcIfaceExpr expr `thenM` \ expr' ->
799 IfaceInlineMe -> returnM (Note InlineMe expr')
800 IfaceSCC cc -> returnM (Note (SCC cc) expr')
801 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
803 -------------------------
804 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
805 = ASSERT( null names )
806 tcIfaceExpr rhs `thenM` \ rhs' ->
807 returnM (DEFAULT, [], rhs')
809 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
810 = ASSERT( null names )
811 tcIfaceExpr rhs `thenM` \ rhs' ->
812 returnM (LitAlt lit, [], rhs')
814 -- A case alternative is made quite a bit more complicated
815 -- by the fact that we omit type annotations because we can
816 -- work them out. True enough, but its not that easy!
817 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
818 = do { con <- tcIfaceDataCon data_occ
820 ; ifM (not (con `elem` tyConDataCons tycon))
821 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
823 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
825 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
826 = ASSERT( isTupleTyCon tycon )
827 do { let [data_con] = tyConDataCons tycon
828 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
830 tcIfaceDataAlt con inst_tys arg_strs rhs
831 = do { us <- newUniqueSupply
832 ; let uniqs = uniqsFromSupply us
833 ; let (ex_tvs, co_tvs, arg_ids)
834 = dataConRepFSInstPat arg_strs uniqs con inst_tys
835 all_tvs = ex_tvs ++ co_tvs
837 ; rhs' <- extendIfaceTyVarEnv all_tvs $
838 extendIfaceIdEnv arg_ids $
840 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
845 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
846 tcExtCoreBindings [] = return []
847 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
849 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
850 do_one (IfaceNonRec bndr rhs) thing_inside
851 = do { rhs' <- tcIfaceExpr rhs
852 ; bndr' <- newExtCoreBndr bndr
853 ; extendIfaceIdEnv [bndr'] $ do
854 { core_binds <- thing_inside
855 ; return (NonRec bndr' rhs' : core_binds) }}
857 do_one (IfaceRec pairs) thing_inside
858 = do { bndrs' <- mappM newExtCoreBndr bndrs
859 ; extendIfaceIdEnv bndrs' $ do
860 { rhss' <- mappM tcIfaceExpr rhss
861 ; core_binds <- thing_inside
862 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
864 (bndrs,rhss) = unzip pairs
868 %************************************************************************
872 %************************************************************************
875 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
876 tcIdInfo ignore_prags name ty info
877 | ignore_prags = return vanillaIdInfo
878 | otherwise = case info of
879 NoInfo -> return vanillaIdInfo
880 HasInfo info -> foldlM tcPrag init_info info
882 -- Set the CgInfo to something sensible but uninformative before
883 -- we start; default assumption is that it has CAFs
884 init_info = vanillaIdInfo
886 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
887 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
888 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
890 -- The next two are lazy, so they don't transitively suck stuff in
891 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
892 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
893 tcPrag info (HsUnfold expr)
894 = tcPragExpr name expr `thenM` \ maybe_expr' ->
896 -- maybe_expr' doesn't get looked at if the unfolding
897 -- is never inspected; so the typecheck doesn't even happen
898 unfold_info = case maybe_expr' of
899 Nothing -> noUnfolding
900 Just expr' -> mkTopUnfolding expr'
902 returnM (info `setUnfoldingInfoLazily` unfold_info)
906 tcWorkerInfo ty info wkr arity
907 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
909 -- We return without testing maybe_wkr_id, but as soon as info is
910 -- looked at we will test it. That's ok, because its outside the
911 -- knot; and there seems no big reason to further defer the
912 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
913 -- over the unfolding until it's actually used does seem worth while.)
914 ; us <- newUniqueSupply
916 ; returnM (case mb_wkr_id of
918 Just wkr_id -> add_wkr_info us wkr_id info) }
920 doc = text "Worker for" <+> ppr wkr
921 add_wkr_info us wkr_id info
922 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
923 `setWorkerInfo` HasWorker wkr_id arity
925 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
927 -- We are relying here on strictness info always appearing
928 -- before worker info, fingers crossed ....
929 strict_sig = case newStrictnessInfo info of
931 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
934 For unfoldings we try to do the job lazily, so that we never type check
935 an unfolding that isn't going to be looked at.
938 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
941 tcIfaceExpr expr `thenM` \ core_expr' ->
943 -- Check for type consistency in the unfolding
944 ifOptM Opt_DoCoreLinting (
945 get_in_scope_ids `thenM` \ in_scope ->
946 case lintUnfolding noSrcLoc in_scope core_expr' of
947 Nothing -> returnM ()
948 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
953 doc = text "Unfolding of" <+> ppr name
954 get_in_scope_ids -- Urgh; but just for linting
956 do { env <- getGblEnv
957 ; case if_rec_types env of {
958 Nothing -> return [] ;
959 Just (_, get_env) -> do
960 { type_env <- get_env
961 ; return (typeEnvIds type_env) }}}
966 %************************************************************************
968 Getting from Names to TyThings
970 %************************************************************************
973 tcIfaceGlobal :: Name -> IfL TyThing
975 | Just thing <- wiredInNameTyThing_maybe name
976 -- Wired-in things include TyCons, DataCons, and Ids
977 = do { ifCheckWiredInThing name; return thing }
979 = do { env <- getGblEnv
980 ; case if_rec_types env of { -- Note [Tying the knot]
981 Just (mod, get_type_env)
982 | nameIsLocalOrFrom mod name
983 -> do -- It's defined in the module being compiled
984 { type_env <- setLclEnv () get_type_env -- yuk
985 ; case lookupNameEnv type_env name of
986 Just thing -> return thing
987 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
988 (ppr name $$ ppr type_env) }
992 { (eps,hpt) <- getEpsAndHpt
994 ; case lookupType dflags hpt (eps_PTE eps) name of {
995 Just thing -> return thing ;
998 { mb_thing <- importDecl name -- It's imported; go get it
1000 Failed err -> failIfM err
1001 Succeeded thing -> return thing
1004 -- Note [Tying the knot]
1005 -- ~~~~~~~~~~~~~~~~~~~~~
1006 -- The if_rec_types field is used in two situations:
1008 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1009 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1010 -- after we've built M's type envt.
1012 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1013 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1014 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1016 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1017 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1018 -- emasculated form (e.g. lacking data constructors).
1020 ifCheckWiredInThing :: Name -> IfL ()
1021 -- Even though we are in an interface file, we want to make
1022 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1023 -- Ditto want to ensure that RULES are loaded too
1024 -- See Note [Loading instances] in LoadIface
1025 ifCheckWiredInThing name
1026 = do { mod <- getIfModule
1027 -- Check whether we are typechecking the interface for this
1028 -- very module. E.g when compiling the base library in --make mode
1029 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1030 -- the HPT, so without the test we'll demand-load it into the PIT!
1031 -- C.f. the same test in checkWiredInTyCon above
1032 ; unless (mod == nameModule name)
1033 (loadWiredInHomeIface name) }
1035 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1036 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1037 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1038 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1039 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1040 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1041 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1042 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1043 ; return (check_tc (tyThingTyCon thing)) }
1046 check_tc tc = case toIfaceTyCon tc of
1048 other -> pprTrace "check_tc" (ppr tc) tc
1052 -- we should be okay just returning Kind constructors without extra loading
1053 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1054 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1055 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1056 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1057 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1059 -- Even though we are in an interface file, we want to make
1060 -- sure the instances and RULES of this tycon are loaded
1061 -- Imagine: f :: Double -> Double
1062 tcWiredInTyCon :: TyCon -> IfL TyCon
1063 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1066 tcIfaceClass :: Name -> IfL Class
1067 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1068 ; return (tyThingClass thing) }
1070 tcIfaceDataCon :: Name -> IfL DataCon
1071 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1073 ADataCon dc -> return dc
1074 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1076 tcIfaceExtId :: Name -> IfL Id
1077 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1079 AnId id -> return id
1080 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1083 %************************************************************************
1087 %************************************************************************
1090 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1091 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1092 = do { name <- newIfaceName (mkVarOccFS fs)
1093 ; ty' <- tcIfaceType ty
1094 ; let id = mkLocalId name ty'
1095 ; extendIfaceIdEnv [id] (thing_inside id) }
1096 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1097 = bindIfaceTyVar bndr thing_inside
1099 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1100 bindIfaceBndrs [] thing_inside = thing_inside []
1101 bindIfaceBndrs (b:bs) thing_inside
1102 = bindIfaceBndr b $ \ b' ->
1103 bindIfaceBndrs bs $ \ bs' ->
1104 thing_inside (b':bs')
1106 -----------------------
1107 tcIfaceLetBndr (IfLetBndr fs ty info)
1108 = do { name <- newIfaceName (mkVarOccFS fs)
1109 ; ty' <- tcIfaceType ty
1111 NoInfo -> return (mkLocalId name ty')
1112 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1114 -- Similar to tcIdInfo, but much simpler
1115 tc_info [] = vanillaIdInfo
1116 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1117 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1118 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1119 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1120 (ppr other) (tc_info i)
1122 -----------------------
1123 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1124 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1125 = do { mod <- getIfModule
1126 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1127 ; ty' <- tcIfaceType ty
1128 ; return (mkLocalId name ty') }
1130 -----------------------
1131 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1132 bindIfaceTyVar (occ,kind) thing_inside
1133 = do { name <- newIfaceName (mkTyVarOcc occ)
1134 ; tyvar <- mk_iface_tyvar name kind
1135 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1137 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1138 bindIfaceTyVars bndrs thing_inside
1139 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1140 ; tyvars <- TcRnMonad.zipWithM mk_iface_tyvar names kinds
1141 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1143 (occs,kinds) = unzip bndrs
1145 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1146 mk_iface_tyvar name ifKind
1147 = do { kind <- tcIfaceType ifKind
1148 ; if isCoercionKind kind then
1149 return (Var.mkCoVar name kind)
1151 return (Var.mkTyVar name kind) }