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 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
17 tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
18 tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
19 tcIfaceVectInfo, tcIfaceGlobal, tcExtCoreBindings
22 #include "HsVersions.h"
73 An IfaceDecl is populated with RdrNames, and these are not renamed to
74 Names before typechecking, because there should be no scope errors etc.
76 -- For (b) consider: f = $(...h....)
77 -- where h is imported, and calls f via an hi-boot file.
78 -- This is bad! But it is not seen as a staging error, because h
79 -- is indeed imported. We don't want the type-checker to black-hole
80 -- when simplifying and compiling the splice!
82 -- Simple solution: discard any unfolding that mentions a variable
83 -- bound in this module (and hence not yet processed).
84 -- The discarding happens when forkM finds a type error.
86 %************************************************************************
88 %* tcImportDecl is the key function for "faulting in" *
91 %************************************************************************
93 The main idea is this. We are chugging along type-checking source code, and
94 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
95 it in the EPS type envt. So it
97 2 gets the decl for GHC.Base.map
98 3 typechecks it via tcIfaceDecl
99 4 and adds it to the type env in the EPS
101 Note that DURING STEP 4, we may find that map's type mentions a type
102 constructor that also
104 Notice that for imported things we read the current version from the EPS
105 mutable variable. This is important in situations like
107 where the code that e1 expands to might import some defns that
108 also turn out to be needed by the code that e2 expands to.
111 tcImportDecl :: Name -> TcM TyThing
112 -- Entry point for *source-code* uses of importDecl
114 | Just thing <- wiredInNameTyThing_maybe name
115 = do { initIfaceTcRn (loadWiredInHomeIface name)
116 -- See Note [Loading instances] in LoadIface
119 = do { traceIf (text "tcImportDecl" <+> ppr name)
120 ; mb_thing <- initIfaceTcRn (importDecl name)
122 Succeeded thing -> return thing
123 Failed err -> failWithTc err }
125 checkWiredInTyCon :: TyCon -> TcM ()
126 -- Ensure that the home module of the TyCon (and hence its instances)
127 -- are loaded. See See Note [Loading instances] in LoadIface
128 -- It might not be a wired-in tycon (see the calls in TcUnify),
129 -- in which case this is a no-op.
131 | not (isWiredInName tc_name)
134 = do { mod <- getModule
135 ; unless (mod == nameModule tc_name)
136 (initIfaceTcRn (loadWiredInHomeIface tc_name))
137 -- Don't look for (non-existent) Float.hi when
138 -- compiling Float.lhs, which mentions Float of course
139 -- A bit yukky to call initIfaceTcRn here
142 tc_name = tyConName tc
144 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
145 -- Get the TyThing for this Name from an interface file
146 -- It's not a wired-in thing -- the caller caught that
148 = ASSERT( not (isWiredInName name) )
151 -- Load the interface, which should populate the PTE
152 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
154 Failed err_msg -> return (Failed err_msg) ;
155 Succeeded iface -> do
157 -- Now look it up again; this time we should find it
159 ; case lookupTypeEnv (eps_PTE eps) name of
160 Just thing -> return (Succeeded thing)
161 Nothing -> return (Failed not_found_msg)
164 nd_doc = ptext SLIT("Need decl for") <+> ppr name
165 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
166 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
167 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
168 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
171 %************************************************************************
173 Type-checking a complete interface
175 %************************************************************************
177 Suppose we discover we don't need to recompile. Then we must type
178 check the old interface file. This is a bit different to the
179 incremental type checking we do as we suck in interface files. Instead
180 we do things similarly as when we are typechecking source decls: we
181 bring into scope the type envt for the interface all at once, using a
182 knot. Remember, the decls aren't necessarily in dependency order --
183 and even if they were, the type decls might be mutually recursive.
186 typecheckIface :: ModIface -- Get the decls from here
187 -> TcRnIf gbl lcl ModDetails
189 = initIfaceTc iface $ \ tc_env_var -> do
190 -- The tc_env_var is freshly allocated, private to
191 -- type-checking this particular interface
192 { -- Get the right set of decls and rules. If we are compiling without -O
193 -- we discard pragmas before typechecking, so that we don't "see"
194 -- information that we shouldn't. From a versioning point of view
195 -- It's not actually *wrong* to do so, but in fact GHCi is unable
196 -- to handle unboxed tuples, so it must not see unfoldings.
197 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
199 -- Typecheck the decls. This is done lazily, so that the knot-tying
200 -- within this single module work out right. In the If monad there is
201 -- no global envt for the current interface; instead, the knot is tied
202 -- through the if_rec_types field of IfGblEnv
203 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
204 ; let type_env = mkNameEnv names_w_things
205 ; writeMutVar tc_env_var type_env
207 -- Now do those rules and instances
208 ; insts <- mapM tcIfaceInst (mi_insts iface)
209 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
210 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
212 -- Vectorisation information
213 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
217 ; exports <- ifaceExportNames (mi_exports iface)
220 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
221 text "Type envt:" <+> ppr type_env])
222 ; return $ ModDetails { md_types = type_env
224 , 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 other -> 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 (mkVanillaGlobal name ty info)) }
364 tcIfaceDecl ignore_prags
365 (IfaceData {ifName = occ_name,
367 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
370 ifGeneric = want_generic,
371 ifFamInst = mb_family })
372 = do { tc_name <- lookupIfaceTop occ_name
373 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
375 { tycon <- fixM ( \ tycon -> do
376 { stupid_theta <- tcIfaceCtxt ctxt
379 Nothing -> return Nothing
381 do { famTyCon <- tcIfaceTyCon fam
382 ; insttys <- mapM tcIfaceType tys
383 ; return $ Just (famTyCon, insttys)
385 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
386 ; buildAlgTyCon tc_name tyvars stupid_theta
387 cons is_rec want_generic gadt_syn famInst
389 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
390 ; return (ATyCon tycon)
393 tcIfaceDecl ignore_prags
394 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
395 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty,
396 ifFamInst = mb_family})
397 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
398 { tc_name <- lookupIfaceTop occ_name
399 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
400 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
401 else SynonymTyCon rhs_tyki
402 ; famInst <- case mb_family of
403 Nothing -> return Nothing
405 do { famTyCon <- tcIfaceTyCon fam
406 ; insttys <- mapM tcIfaceType tys
407 ; return $ Just (famTyCon, insttys)
409 ; tycon <- buildSynTyCon tc_name tyvars rhs famInst
410 ; return $ ATyCon tycon
413 tcIfaceDecl ignore_prags
414 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
415 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
416 ifATs = rdr_ats, ifSigs = rdr_sigs,
418 -- ToDo: in hs-boot files we should really treat abstract classes specially,
419 -- as we do abstract tycons
420 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
421 { cls_name <- lookupIfaceTop occ_name
422 ; ctxt <- tcIfaceCtxt rdr_ctxt
423 ; sigs <- mapM tc_sig rdr_sigs
424 ; fds <- mapM tc_fd rdr_fds
425 ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
426 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
427 ; cls <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
428 ; return (AClass cls) }
430 tc_sig (IfaceClassOp occ dm rdr_ty)
431 = do { op_name <- lookupIfaceTop occ
432 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
433 -- Must be done lazily for just the same reason as the
434 -- type of a data con; to avoid sucking in types that
435 -- it mentions unless it's necessray to do so
436 ; return (op_name, dm, op_ty) }
438 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
440 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
441 ; tvs2' <- mapM tcIfaceTyVar tvs2
442 ; return (tvs1', tvs2') }
444 -- For each AT argument compute the position of the corresponding class
445 -- parameter in the class head. This will later serve as a permutation
446 -- vector when checking the validity of instance declarations.
447 setTyThingPoss (ATyCon tycon) atTyVars =
448 let classTyVars = map fst tv_bndrs
450 . map ((`elemIndex` classTyVars) . fst)
452 -- There will be no Nothing, as we already passed renaming
454 ATyCon (setTyConArgPoss tycon poss)
455 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
457 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
458 = do { name <- lookupIfaceTop rdr_name
459 ; return (ATyCon (mkForeignTyCon name ext_name
462 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
464 IfAbstractTyCon -> return mkAbstractTyConRhs
465 IfOpenDataTyCon -> return mkOpenDataTyConRhs
466 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
467 ; return (mkDataTyConRhs data_cons) }
468 IfNewTyCon con -> do { data_con <- tc_con_decl con
469 ; mkNewTyConRhs tycon_name tycon data_con }
471 tc_con_decl (IfCon { ifConInfix = is_infix,
472 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
473 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
474 ifConArgTys = args, ifConFields = field_lbls,
475 ifConStricts = stricts})
476 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
477 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
478 { name <- lookupIfaceTop occ
479 ; eq_spec <- tcIfaceEqSpec spec
480 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
481 -- At one stage I thought that this context checking *had*
482 -- to be lazy, because of possible mutual recursion between the
483 -- type and the classe:
485 -- class Real a where { toRat :: a -> Ratio Integer }
486 -- data (Real a) => Ratio a = ...
487 -- But now I think that the laziness in checking class ops breaks
488 -- the loop, so no laziness needed
490 -- Read the argument types, but lazily to avoid faulting in
491 -- the component types unless they are really needed
492 ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
493 ; lbl_names <- mapM lookupIfaceTop field_lbls
495 ; buildDataCon name is_infix {- Not infix -}
497 univ_tyvars ex_tyvars
501 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
506 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
507 ; ty <- tcIfaceType if_ty
512 %************************************************************************
516 %************************************************************************
519 tcIfaceInst :: IfaceInst -> IfL Instance
520 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
521 ifInstCls = cls, ifInstTys = mb_tcs,
523 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
524 tcIfaceExtId dfun_occ
525 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
526 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
528 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
529 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
530 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
531 -- { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
532 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
533 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
535 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
536 return (mkImportedFamInst fam mb_tcs' tycon')
540 %************************************************************************
544 %************************************************************************
546 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
547 are in the type environment. However, remember that typechecking a Rule may
548 (as a side effect) augment the type envt, and so we may need to iterate the process.
551 tcIfaceRules :: Bool -- True <=> ignore rules
554 tcIfaceRules ignore_prags if_rules
555 | ignore_prags = return []
556 | otherwise = mapM tcIfaceRule if_rules
558 tcIfaceRule :: IfaceRule -> IfL CoreRule
559 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
560 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
562 = do { ~(bndrs', args', rhs') <-
563 -- Typecheck the payload lazily, in the hope it'll never be looked at
564 forkM (ptext SLIT("Rule") <+> ftext name) $
565 bindIfaceBndrs bndrs $ \ bndrs' ->
566 do { args' <- mapM tcIfaceExpr args
567 ; rhs' <- tcIfaceExpr rhs
568 ; return (bndrs', args', rhs') }
569 ; let mb_tcs = map ifTopFreeName args
570 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
571 ru_bndrs = bndrs', ru_args = args',
574 ru_local = False }) } -- An imported RULE is never for a local Id
575 -- or, even if it is (module loop, perhaps)
576 -- we'll just leave it in the non-local set
578 -- This function *must* mirror exactly what Rules.topFreeName does
579 -- We could have stored the ru_rough field in the iface file
580 -- but that would be redundant, I think.
581 -- The only wrinkle is that we must not be deceived by
582 -- type syononyms at the top of a type arg. Since
583 -- we can't tell at this point, we are careful not
584 -- to write them out in coreRuleToIfaceRule
585 ifTopFreeName :: IfaceExpr -> Maybe Name
586 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
587 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
588 ifTopFreeName (IfaceExt n) = Just n
589 ifTopFreeName other = Nothing
593 %************************************************************************
595 Vectorisation information
597 %************************************************************************
600 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
601 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
602 { ifaceVectInfoVar = vars
603 , ifaceVectInfoTyCon = tycons
604 , ifaceVectInfoTyConReuse = tyconsReuse
606 = do { vVars <- mapM vectVarMapping vars
607 ; tyConRes1 <- mapM vectTyConMapping tycons
608 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
609 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
611 { vectInfoVar = mkVarEnv vVars
612 , vectInfoTyCon = mkNameEnv vTyCons
613 , vectInfoDataCon = mkNameEnv (concat vDataCons)
614 , vectInfoPADFun = mkNameEnv vPAs
615 , vectInfoIso = mkNameEnv vIsos
620 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
621 ; let { var = lookupVar name
622 ; vVar = lookupVar vName
624 ; return (var, (var, vVar))
626 vectTyConMapping name
627 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
628 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
629 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
630 ; let { tycon = lookupTyCon name
631 ; vTycon = lookupTyCon vName
632 ; paTycon = lookupVar paName
633 ; isoTycon = lookupVar isoName
635 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
636 ; return ((name, (tycon, vTycon)), -- (T, T_v)
637 vDataCons, -- list of (Ci, Ci_v)
638 (vName, (vTycon, paTycon)), -- (T_v, paT)
639 (name, (tycon, isoTycon))) -- (T, isoT)
641 vectTyConReuseMapping name
642 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
643 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
644 ; let { tycon = lookupTyCon name
645 ; paTycon = lookupVar paName
646 ; isoTycon = lookupVar isoName
647 ; vDataCons = [ (dataConName dc, (dc, dc))
648 | dc <- tyConDataCons tycon]
650 ; return ((name, (tycon, tycon)), -- (T, T)
651 vDataCons, -- list of (Ci, Ci)
652 (name, (tycon, paTycon)), -- (T, paT)
653 (name, (tycon, isoTycon))) -- (T, isoT)
655 vectDataConMapping datacon
656 = do { let name = dataConName datacon
657 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
658 ; let vDataCon = lookupDataCon vName
659 ; return (name, (datacon, vDataCon))
662 lookupVar name = case lookupTypeEnv typeEnv name of
663 Just (AnId var) -> var
665 panic "TcIface.tcIfaceVectInfo: not an id"
667 panic "TcIface.tcIfaceVectInfo: unknown name"
668 lookupTyCon name = case lookupTypeEnv typeEnv name of
669 Just (ATyCon tc) -> tc
671 panic "TcIface.tcIfaceVectInfo: not a tycon"
673 panic "TcIface.tcIfaceVectInfo: unknown name"
674 lookupDataCon name = case lookupTypeEnv typeEnv name of
675 Just (ADataCon dc) -> dc
677 panic "TcIface.tcIfaceVectInfo: not a datacon"
679 panic "TcIface.tcIfaceVectInfo: unknown name"
682 %************************************************************************
686 %************************************************************************
689 tcIfaceType :: IfaceType -> IfL Type
690 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
691 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
692 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
693 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
694 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
695 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
697 tcIfaceTypes tys = mapM tcIfaceType tys
699 -----------------------------------------
700 tcIfacePredType :: IfacePredType -> IfL PredType
701 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
702 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
703 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
705 -----------------------------------------
706 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
707 tcIfaceCtxt sts = mapM tcIfacePredType sts
711 %************************************************************************
715 %************************************************************************
718 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
719 tcIfaceExpr (IfaceType ty)
720 = Type <$> tcIfaceType ty
722 tcIfaceExpr (IfaceLcl name)
723 = Var <$> tcIfaceLclId name
725 tcIfaceExpr (IfaceTick modName tickNo)
726 = Var <$> tcIfaceTick modName tickNo
728 tcIfaceExpr (IfaceExt gbl)
729 = Var <$> tcIfaceExtId gbl
731 tcIfaceExpr (IfaceLit lit)
734 tcIfaceExpr (IfaceFCall cc ty) = do
735 ty' <- tcIfaceType ty
737 return (Var (mkFCallId u cc ty'))
739 tcIfaceExpr (IfaceTuple boxity args) = do
740 args' <- mapM tcIfaceExpr args
741 -- Put the missing type arguments back in
742 let con_args = map (Type . exprType) args' ++ args'
743 return (mkApps (Var con_id) con_args)
746 con_id = dataConWorkId (tupleCon boxity arity)
749 tcIfaceExpr (IfaceLam bndr body)
750 = bindIfaceBndr bndr $ \bndr' ->
751 Lam bndr' <$> tcIfaceExpr body
753 tcIfaceExpr (IfaceApp fun arg)
754 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
756 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
757 scrut' <- tcIfaceExpr scrut
758 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
760 scrut_ty = exprType scrut'
761 case_bndr' = mkLocalId case_bndr_name scrut_ty
762 tc_app = splitTyConApp scrut_ty
763 -- NB: Won't always succeed (polymoprhic case)
764 -- but won't be demanded in those cases
765 -- NB: not tcSplitTyConApp; we are looking at Core here
766 -- look through non-rec newtypes to find the tycon that
767 -- corresponds to the datacon in this case alternative
769 extendIfaceIdEnv [case_bndr'] $ do
770 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
771 ty' <- tcIfaceType ty
772 return (Case scrut' case_bndr' ty' alts')
774 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
775 rhs' <- tcIfaceExpr rhs
776 id <- tcIfaceLetBndr bndr
777 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
778 return (Let (NonRec id rhs') body')
780 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
781 ids <- mapM tcIfaceLetBndr bndrs
782 extendIfaceIdEnv ids $ do
783 rhss' <- mapM tcIfaceExpr rhss
784 body' <- tcIfaceExpr body
785 return (Let (Rec (ids `zip` rhss')) body')
787 (bndrs, rhss) = unzip pairs
789 tcIfaceExpr (IfaceCast expr co) = do
790 expr' <- tcIfaceExpr expr
791 co' <- tcIfaceType co
792 return (Cast expr' co')
794 tcIfaceExpr (IfaceNote note expr) = do
795 expr' <- tcIfaceExpr expr
797 IfaceInlineMe -> return (Note InlineMe expr')
798 IfaceSCC cc -> return (Note (SCC cc) expr')
799 IfaceCoreNote n -> return (Note (CoreNote n) expr')
801 -------------------------
802 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
803 = ASSERT( null names ) do
804 rhs' <- tcIfaceExpr rhs
805 return (DEFAULT, [], rhs')
807 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
808 = ASSERT( null names ) do
809 rhs' <- tcIfaceExpr rhs
810 return (LitAlt lit, [], rhs')
812 -- A case alternative is made quite a bit more complicated
813 -- by the fact that we omit type annotations because we can
814 -- work them out. True enough, but its not that easy!
815 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
816 = do { con <- tcIfaceDataCon data_occ
817 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
818 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
819 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
821 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
822 = ASSERT( isTupleTyCon tycon )
823 do { let [data_con] = tyConDataCons tycon
824 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
826 tcIfaceDataAlt con inst_tys arg_strs rhs
827 = do { us <- newUniqueSupply
828 ; let uniqs = uniqsFromSupply us
829 ; let (ex_tvs, co_tvs, arg_ids)
830 = dataConRepFSInstPat arg_strs uniqs con inst_tys
831 all_tvs = ex_tvs ++ co_tvs
833 ; rhs' <- extendIfaceTyVarEnv all_tvs $
834 extendIfaceIdEnv arg_ids $
836 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
841 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
842 tcExtCoreBindings [] = return []
843 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
845 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
846 do_one (IfaceNonRec bndr rhs) thing_inside
847 = do { rhs' <- tcIfaceExpr rhs
848 ; bndr' <- newExtCoreBndr bndr
849 ; extendIfaceIdEnv [bndr'] $ do
850 { core_binds <- thing_inside
851 ; return (NonRec bndr' rhs' : core_binds) }}
853 do_one (IfaceRec pairs) thing_inside
854 = do { bndrs' <- mapM newExtCoreBndr bndrs
855 ; extendIfaceIdEnv bndrs' $ do
856 { rhss' <- mapM tcIfaceExpr rhss
857 ; core_binds <- thing_inside
858 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
860 (bndrs,rhss) = unzip pairs
864 %************************************************************************
868 %************************************************************************
871 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
872 tcIdInfo ignore_prags name ty info
873 | ignore_prags = return vanillaIdInfo
874 | otherwise = case info of
875 NoInfo -> return vanillaIdInfo
876 HasInfo info -> foldlM tcPrag init_info info
878 -- Set the CgInfo to something sensible but uninformative before
879 -- we start; default assumption is that it has CAFs
880 init_info = vanillaIdInfo
882 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
883 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
884 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
886 -- The next two are lazy, so they don't transitively suck stuff in
887 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
888 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
889 tcPrag info (HsUnfold expr) = do
890 maybe_expr' <- tcPragExpr name expr
892 -- maybe_expr' doesn't get looked at if the unfolding
893 -- is never inspected; so the typecheck doesn't even happen
894 unfold_info = case maybe_expr' of
895 Nothing -> noUnfolding
896 Just expr' -> mkTopUnfolding expr'
897 return (info `setUnfoldingInfoLazily` unfold_info)
901 tcWorkerInfo ty info wkr arity
902 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
904 -- We return without testing maybe_wkr_id, but as soon as info is
905 -- looked at we will test it. That's ok, because its outside the
906 -- knot; and there seems no big reason to further defer the
907 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
908 -- over the unfolding until it's actually used does seem worth while.)
909 ; us <- newUniqueSupply
911 ; return (case mb_wkr_id of
913 Just wkr_id -> add_wkr_info us wkr_id info) }
915 doc = text "Worker for" <+> ppr wkr
916 add_wkr_info us wkr_id info
917 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
918 `setWorkerInfo` HasWorker wkr_id arity
920 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
922 -- We are relying here on strictness info always appearing
923 -- before worker info, fingers crossed ....
924 strict_sig = case newStrictnessInfo info of
926 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
929 For unfoldings we try to do the job lazily, so that we never type check
930 an unfolding that isn't going to be looked at.
933 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
935 = forkM_maybe doc $ do
936 core_expr' <- tcIfaceExpr expr
938 -- Check for type consistency in the unfolding
939 ifOptM Opt_DoCoreLinting $ do
940 in_scope <- get_in_scope_ids
941 case lintUnfolding noSrcLoc in_scope core_expr' of
943 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
947 doc = text "Unfolding of" <+> ppr name
948 get_in_scope_ids -- Urgh; but just for linting
950 do { env <- getGblEnv
951 ; case if_rec_types env of {
952 Nothing -> return [] ;
953 Just (_, get_env) -> do
954 { type_env <- get_env
955 ; return (typeEnvIds type_env) }}}
960 %************************************************************************
962 Getting from Names to TyThings
964 %************************************************************************
967 tcIfaceGlobal :: Name -> IfL TyThing
969 | Just thing <- wiredInNameTyThing_maybe name
970 -- Wired-in things include TyCons, DataCons, and Ids
971 = do { ifCheckWiredInThing name; return thing }
973 = do { env <- getGblEnv
974 ; case if_rec_types env of { -- Note [Tying the knot]
975 Just (mod, get_type_env)
976 | nameIsLocalOrFrom mod name
977 -> do -- It's defined in the module being compiled
978 { type_env <- setLclEnv () get_type_env -- yuk
979 ; case lookupNameEnv type_env name of
980 Just thing -> return thing
981 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
982 (ppr name $$ ppr type_env) }
986 { (eps,hpt) <- getEpsAndHpt
988 ; case lookupType dflags hpt (eps_PTE eps) name of {
989 Just thing -> return thing ;
992 { mb_thing <- importDecl name -- It's imported; go get it
994 Failed err -> failIfM err
995 Succeeded thing -> return thing
998 -- Note [Tying the knot]
999 -- ~~~~~~~~~~~~~~~~~~~~~
1000 -- The if_rec_types field is used in two situations:
1002 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1003 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1004 -- after we've built M's type envt.
1006 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1007 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1008 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1010 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1011 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1012 -- emasculated form (e.g. lacking data constructors).
1014 ifCheckWiredInThing :: Name -> IfL ()
1015 -- Even though we are in an interface file, we want to make
1016 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1017 -- Ditto want to ensure that RULES are loaded too
1018 -- See Note [Loading instances] in LoadIface
1019 ifCheckWiredInThing name
1020 = do { mod <- getIfModule
1021 -- Check whether we are typechecking the interface for this
1022 -- very module. E.g when compiling the base library in --make mode
1023 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1024 -- the HPT, so without the test we'll demand-load it into the PIT!
1025 -- C.f. the same test in checkWiredInTyCon above
1026 ; unless (mod == nameModule name)
1027 (loadWiredInHomeIface name) }
1029 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1030 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1031 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1032 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1033 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1034 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1035 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1036 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1037 ; return (check_tc (tyThingTyCon thing)) }
1040 | debugIsOn = case toIfaceTyCon tc of
1042 other -> pprTrace "check_tc" (ppr tc) tc
1044 -- we should be okay just returning Kind constructors without extra loading
1045 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1046 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1047 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1048 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1049 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1051 -- Even though we are in an interface file, we want to make
1052 -- sure the instances and RULES of this tycon are loaded
1053 -- Imagine: f :: Double -> Double
1054 tcWiredInTyCon :: TyCon -> IfL TyCon
1055 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1058 tcIfaceClass :: Name -> IfL Class
1059 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1060 ; return (tyThingClass thing) }
1062 tcIfaceDataCon :: Name -> IfL DataCon
1063 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1065 ADataCon dc -> return dc
1066 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1068 tcIfaceExtId :: Name -> IfL Id
1069 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1071 AnId id -> return id
1072 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1075 %************************************************************************
1079 %************************************************************************
1082 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1083 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1084 = do { name <- newIfaceName (mkVarOccFS fs)
1085 ; ty' <- tcIfaceType ty
1086 ; let id = mkLocalId name ty'
1087 ; extendIfaceIdEnv [id] (thing_inside id) }
1088 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1089 = bindIfaceTyVar bndr thing_inside
1091 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1092 bindIfaceBndrs [] thing_inside = thing_inside []
1093 bindIfaceBndrs (b:bs) thing_inside
1094 = bindIfaceBndr b $ \ b' ->
1095 bindIfaceBndrs bs $ \ bs' ->
1096 thing_inside (b':bs')
1098 -----------------------
1099 tcIfaceLetBndr (IfLetBndr fs ty info)
1100 = do { name <- newIfaceName (mkVarOccFS fs)
1101 ; ty' <- tcIfaceType ty
1103 NoInfo -> return (mkLocalId name ty')
1104 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1106 -- Similar to tcIdInfo, but much simpler
1107 tc_info [] = vanillaIdInfo
1108 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1109 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1110 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1111 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1112 (ppr other) (tc_info i)
1114 -----------------------
1115 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1116 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1117 = do { mod <- getIfModule
1118 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1119 ; ty' <- tcIfaceType ty
1120 ; return (mkLocalId name ty') }
1122 -----------------------
1123 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1124 bindIfaceTyVar (occ,kind) thing_inside
1125 = do { name <- newIfaceName (mkTyVarOcc occ)
1126 ; tyvar <- mk_iface_tyvar name kind
1127 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1129 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1130 bindIfaceTyVars bndrs thing_inside
1131 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1132 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1133 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1135 (occs,kinds) = unzip bndrs
1137 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1138 mk_iface_tyvar name ifKind
1139 = do { kind <- tcIfaceType ifKind
1140 ; if isCoercionKind kind then
1141 return (Var.mkCoVar name kind)
1143 return (Var.mkTyVar name kind) }