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/WorkingConventions#Warnings
17 tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
18 tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
19 tcIfaceVectInfo, tcIfaceGlobal, tcExtCoreBindings
22 #include "HsVersions.h"
72 An IfaceDecl is populated with RdrNames, and these are not renamed to
73 Names before typechecking, because there should be no scope errors etc.
75 -- For (b) consider: f = $(...h....)
76 -- where h is imported, and calls f via an hi-boot file.
77 -- This is bad! But it is not seen as a staging error, because h
78 -- is indeed imported. We don't want the type-checker to black-hole
79 -- when simplifying and compiling the splice!
81 -- Simple solution: discard any unfolding that mentions a variable
82 -- bound in this module (and hence not yet processed).
83 -- The discarding happens when forkM finds a type error.
85 %************************************************************************
87 %* tcImportDecl is the key function for "faulting in" *
90 %************************************************************************
92 The main idea is this. We are chugging along type-checking source code, and
93 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
94 it in the EPS type envt. So it
96 2 gets the decl for GHC.Base.map
97 3 typechecks it via tcIfaceDecl
98 4 and adds it to the type env in the EPS
100 Note that DURING STEP 4, we may find that map's type mentions a type
101 constructor that also
103 Notice that for imported things we read the current version from the EPS
104 mutable variable. This is important in situations like
106 where the code that e1 expands to might import some defns that
107 also turn out to be needed by the code that e2 expands to.
110 tcImportDecl :: Name -> TcM TyThing
111 -- Entry point for *source-code* uses of importDecl
113 | Just thing <- wiredInNameTyThing_maybe name
114 = do { initIfaceTcRn (loadWiredInHomeIface name)
115 -- See Note [Loading instances] in LoadIface
118 = do { traceIf (text "tcImportDecl" <+> ppr name)
119 ; mb_thing <- initIfaceTcRn (importDecl name)
121 Succeeded thing -> return thing
122 Failed err -> failWithTc err }
124 checkWiredInTyCon :: TyCon -> TcM ()
125 -- Ensure that the home module of the TyCon (and hence its instances)
126 -- are loaded. See See Note [Loading instances] in LoadIface
127 -- It might not be a wired-in tycon (see the calls in TcUnify),
128 -- in which case this is a no-op.
130 | not (isWiredInName tc_name)
133 = do { mod <- getModule
134 ; unless (mod == nameModule tc_name)
135 (initIfaceTcRn (loadWiredInHomeIface tc_name))
136 -- Don't look for (non-existent) Float.hi when
137 -- compiling Float.lhs, which mentions Float of course
138 -- A bit yukky to call initIfaceTcRn here
141 tc_name = tyConName tc
143 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
144 -- Get the TyThing for this Name from an interface file
145 -- It's not a wired-in thing -- the caller caught that
147 = ASSERT( not (isWiredInName name) )
150 -- Load the interface, which should populate the PTE
151 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
153 Failed err_msg -> return (Failed err_msg) ;
154 Succeeded iface -> do
156 -- Now look it up again; this time we should find it
158 ; case lookupTypeEnv (eps_PTE eps) name of
159 Just thing -> return (Succeeded thing)
160 Nothing -> return (Failed not_found_msg)
163 nd_doc = ptext SLIT("Need decl for") <+> ppr name
164 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
165 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
166 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
167 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
170 %************************************************************************
172 Type-checking a complete interface
174 %************************************************************************
176 Suppose we discover we don't need to recompile. Then we must type
177 check the old interface file. This is a bit different to the
178 incremental type checking we do as we suck in interface files. Instead
179 we do things similarly as when we are typechecking source decls: we
180 bring into scope the type envt for the interface all at once, using a
181 knot. Remember, the decls aren't necessarily in dependency order --
182 and even if they were, the type decls might be mutually recursive.
185 typecheckIface :: ModIface -- Get the decls from here
186 -> TcRnIf gbl lcl ModDetails
188 = initIfaceTc iface $ \ tc_env_var -> do
189 -- The tc_env_var is freshly allocated, private to
190 -- type-checking this particular interface
191 { -- Get the right set of decls and rules. If we are compiling without -O
192 -- we discard pragmas before typechecking, so that we don't "see"
193 -- information that we shouldn't. From a versioning point of view
194 -- It's not actually *wrong* to do so, but in fact GHCi is unable
195 -- to handle unboxed tuples, so it must not see unfoldings.
196 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
198 -- Typecheck the decls. This is done lazily, so that the knot-tying
199 -- within this single module work out right. In the If monad there is
200 -- no global envt for the current interface; instead, the knot is tied
201 -- through the if_rec_types field of IfGblEnv
202 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
203 ; let type_env = mkNameEnv names_w_things
204 ; writeMutVar tc_env_var type_env
206 -- Now do those rules and instances
207 ; insts <- mapM tcIfaceInst (mi_insts iface)
208 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
209 ; rules <- tcIfaceRules ignore_prags (mi_rules 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
225 , md_vect_info = vect_info
226 , md_exports = exports
227 , md_modBreaks = emptyModBreaks
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 <- mappM tc_sig rdr_sigs
424 ; fds <- mappM tc_fd rdr_fds
425 ; ats' <- mappM (tcIfaceDecl ignore_prags) rdr_ats
426 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
427 ; cls <- buildClass 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' <- mappM tcIfaceTyVar tvs1
441 ; tvs2' <- mappM 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 <- mappM 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) (mappM tcIfaceType args)
493 ; lbl_names <- mappM 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 -- = do { 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' <- mappM tcIfaceExpr args
567 ; rhs' <- tcIfaceExpr rhs
568 ; return (bndrs', args', rhs') }
569 ; let mb_tcs = map ifTopFreeName args
570 ; returnM (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 tycons
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 = mappM tcIfacePredType sts
711 %************************************************************************
715 %************************************************************************
718 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
719 tcIfaceExpr (IfaceType ty)
720 = tcIfaceType ty `thenM` \ ty' ->
723 tcIfaceExpr (IfaceLcl name)
724 = tcIfaceLclId name `thenM` \ id ->
727 tcIfaceExpr (IfaceTick modName tickNo)
728 = tcIfaceTick modName tickNo `thenM` \ id ->
731 tcIfaceExpr (IfaceExt gbl)
732 = tcIfaceExtId gbl `thenM` \ id ->
735 tcIfaceExpr (IfaceLit lit)
738 tcIfaceExpr (IfaceFCall cc ty)
739 = tcIfaceType ty `thenM` \ ty' ->
740 newUnique `thenM` \ u ->
741 returnM (Var (mkFCallId u cc ty'))
743 tcIfaceExpr (IfaceTuple boxity args)
744 = mappM tcIfaceExpr args `thenM` \ args' ->
746 -- Put the missing type arguments back in
747 con_args = map (Type . exprType) args' ++ args'
749 returnM (mkApps (Var con_id) con_args)
752 con_id = dataConWorkId (tupleCon boxity arity)
755 tcIfaceExpr (IfaceLam bndr body)
756 = bindIfaceBndr bndr $ \ bndr' ->
757 tcIfaceExpr body `thenM` \ body' ->
758 returnM (Lam bndr' body')
760 tcIfaceExpr (IfaceApp fun arg)
761 = tcIfaceExpr fun `thenM` \ fun' ->
762 tcIfaceExpr arg `thenM` \ arg' ->
763 returnM (App fun' arg')
765 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)
766 = tcIfaceExpr scrut `thenM` \ scrut' ->
767 newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
769 scrut_ty = exprType scrut'
770 case_bndr' = mkLocalId case_bndr_name scrut_ty
771 tc_app = splitTyConApp scrut_ty
772 -- NB: Won't always succeed (polymoprhic case)
773 -- but won't be demanded in those cases
774 -- NB: not tcSplitTyConApp; we are looking at Core here
775 -- look through non-rec newtypes to find the tycon that
776 -- corresponds to the datacon in this case alternative
778 extendIfaceIdEnv [case_bndr'] $
779 mappM (tcIfaceAlt scrut' tc_app) alts `thenM` \ alts' ->
780 tcIfaceType ty `thenM` \ ty' ->
781 returnM (Case scrut' case_bndr' ty' alts')
783 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
784 = do { rhs' <- tcIfaceExpr rhs
785 ; id <- tcIfaceLetBndr bndr
786 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
787 ; return (Let (NonRec id rhs') body') }
789 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
790 = do { ids <- mapM tcIfaceLetBndr bndrs
791 ; extendIfaceIdEnv ids $ do
792 { rhss' <- mapM tcIfaceExpr rhss
793 ; body' <- tcIfaceExpr body
794 ; return (Let (Rec (ids `zip` rhss')) body') } }
796 (bndrs, rhss) = unzip pairs
798 tcIfaceExpr (IfaceCast expr co) = do
799 expr' <- tcIfaceExpr expr
800 co' <- tcIfaceType co
801 returnM (Cast expr' co')
803 tcIfaceExpr (IfaceNote note expr)
804 = tcIfaceExpr expr `thenM` \ expr' ->
806 IfaceInlineMe -> returnM (Note InlineMe expr')
807 IfaceSCC cc -> returnM (Note (SCC cc) expr')
808 IfaceCoreNote n -> returnM (Note (CoreNote n) expr')
810 -------------------------
811 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
812 = ASSERT( null names )
813 tcIfaceExpr rhs `thenM` \ rhs' ->
814 returnM (DEFAULT, [], rhs')
816 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
817 = ASSERT( null names )
818 tcIfaceExpr rhs `thenM` \ rhs' ->
819 returnM (LitAlt lit, [], rhs')
821 -- A case alternative is made quite a bit more complicated
822 -- by the fact that we omit type annotations because we can
823 -- work them out. True enough, but its not that easy!
824 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
825 = do { con <- tcIfaceDataCon data_occ
827 ; ifM (not (con `elem` tyConDataCons tycon))
828 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
830 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
832 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
833 = ASSERT( isTupleTyCon tycon )
834 do { let [data_con] = tyConDataCons tycon
835 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
837 tcIfaceDataAlt con inst_tys arg_strs rhs
838 = do { us <- newUniqueSupply
839 ; let uniqs = uniqsFromSupply us
840 ; let (ex_tvs, co_tvs, arg_ids)
841 = dataConRepFSInstPat arg_strs uniqs con inst_tys
842 all_tvs = ex_tvs ++ co_tvs
844 ; rhs' <- extendIfaceTyVarEnv all_tvs $
845 extendIfaceIdEnv arg_ids $
847 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
852 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
853 tcExtCoreBindings [] = return []
854 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
856 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
857 do_one (IfaceNonRec bndr rhs) thing_inside
858 = do { rhs' <- tcIfaceExpr rhs
859 ; bndr' <- newExtCoreBndr bndr
860 ; extendIfaceIdEnv [bndr'] $ do
861 { core_binds <- thing_inside
862 ; return (NonRec bndr' rhs' : core_binds) }}
864 do_one (IfaceRec pairs) thing_inside
865 = do { bndrs' <- mappM newExtCoreBndr bndrs
866 ; extendIfaceIdEnv bndrs' $ do
867 { rhss' <- mappM tcIfaceExpr rhss
868 ; core_binds <- thing_inside
869 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
871 (bndrs,rhss) = unzip pairs
875 %************************************************************************
879 %************************************************************************
882 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
883 tcIdInfo ignore_prags name ty info
884 | ignore_prags = return vanillaIdInfo
885 | otherwise = case info of
886 NoInfo -> return vanillaIdInfo
887 HasInfo info -> foldlM tcPrag init_info info
889 -- Set the CgInfo to something sensible but uninformative before
890 -- we start; default assumption is that it has CAFs
891 init_info = vanillaIdInfo
893 tcPrag info HsNoCafRefs = returnM (info `setCafInfo` NoCafRefs)
894 tcPrag info (HsArity arity) = returnM (info `setArityInfo` arity)
895 tcPrag info (HsStrictness str) = returnM (info `setAllStrictnessInfo` Just str)
897 -- The next two are lazy, so they don't transitively suck stuff in
898 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
899 tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
900 tcPrag info (HsUnfold expr)
901 = tcPragExpr name expr `thenM` \ maybe_expr' ->
903 -- maybe_expr' doesn't get looked at if the unfolding
904 -- is never inspected; so the typecheck doesn't even happen
905 unfold_info = case maybe_expr' of
906 Nothing -> noUnfolding
907 Just expr' -> mkTopUnfolding expr'
909 returnM (info `setUnfoldingInfoLazily` unfold_info)
913 tcWorkerInfo ty info wkr arity
914 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
916 -- We return without testing maybe_wkr_id, but as soon as info is
917 -- looked at we will test it. That's ok, because its outside the
918 -- knot; and there seems no big reason to further defer the
919 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
920 -- over the unfolding until it's actually used does seem worth while.)
921 ; us <- newUniqueSupply
923 ; returnM (case mb_wkr_id of
925 Just wkr_id -> add_wkr_info us wkr_id info) }
927 doc = text "Worker for" <+> ppr wkr
928 add_wkr_info us wkr_id info
929 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
930 `setWorkerInfo` HasWorker wkr_id arity
932 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
934 -- We are relying here on strictness info always appearing
935 -- before worker info, fingers crossed ....
936 strict_sig = case newStrictnessInfo info of
938 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
941 For unfoldings we try to do the job lazily, so that we never type check
942 an unfolding that isn't going to be looked at.
945 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
948 tcIfaceExpr expr `thenM` \ core_expr' ->
950 -- Check for type consistency in the unfolding
951 ifOptM Opt_DoCoreLinting (
952 get_in_scope_ids `thenM` \ in_scope ->
953 case lintUnfolding noSrcLoc in_scope core_expr' of
954 Nothing -> returnM ()
955 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
960 doc = text "Unfolding of" <+> ppr name
961 get_in_scope_ids -- Urgh; but just for linting
963 do { env <- getGblEnv
964 ; case if_rec_types env of {
965 Nothing -> return [] ;
966 Just (_, get_env) -> do
967 { type_env <- get_env
968 ; return (typeEnvIds type_env) }}}
973 %************************************************************************
975 Getting from Names to TyThings
977 %************************************************************************
980 tcIfaceGlobal :: Name -> IfL TyThing
982 | Just thing <- wiredInNameTyThing_maybe name
983 -- Wired-in things include TyCons, DataCons, and Ids
984 = do { ifCheckWiredInThing name; return thing }
986 = do { env <- getGblEnv
987 ; case if_rec_types env of { -- Note [Tying the knot]
988 Just (mod, get_type_env)
989 | nameIsLocalOrFrom mod name
990 -> do -- It's defined in the module being compiled
991 { type_env <- setLclEnv () get_type_env -- yuk
992 ; case lookupNameEnv type_env name of
993 Just thing -> return thing
994 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
995 (ppr name $$ ppr type_env) }
999 { (eps,hpt) <- getEpsAndHpt
1000 ; dflags <- getDOpts
1001 ; case lookupType dflags hpt (eps_PTE eps) name of {
1002 Just thing -> return thing ;
1005 { mb_thing <- importDecl name -- It's imported; go get it
1007 Failed err -> failIfM err
1008 Succeeded thing -> return thing
1011 -- Note [Tying the knot]
1012 -- ~~~~~~~~~~~~~~~~~~~~~
1013 -- The if_rec_types field is used in two situations:
1015 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1016 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1017 -- after we've built M's type envt.
1019 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1020 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1021 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1023 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1024 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1025 -- emasculated form (e.g. lacking data constructors).
1027 ifCheckWiredInThing :: Name -> IfL ()
1028 -- Even though we are in an interface file, we want to make
1029 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1030 -- Ditto want to ensure that RULES are loaded too
1031 -- See Note [Loading instances] in LoadIface
1032 ifCheckWiredInThing name
1033 = do { mod <- getIfModule
1034 -- Check whether we are typechecking the interface for this
1035 -- very module. E.g when compiling the base library in --make mode
1036 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1037 -- the HPT, so without the test we'll demand-load it into the PIT!
1038 -- C.f. the same test in checkWiredInTyCon above
1039 ; unless (mod == nameModule name)
1040 (loadWiredInHomeIface name) }
1042 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1043 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1044 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1045 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1046 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1047 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1048 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1049 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1050 ; return (check_tc (tyThingTyCon thing)) }
1053 check_tc tc = case toIfaceTyCon tc of
1055 other -> pprTrace "check_tc" (ppr tc) tc
1059 -- we should be okay just returning Kind constructors without extra loading
1060 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1061 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1062 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1063 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1064 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1066 -- Even though we are in an interface file, we want to make
1067 -- sure the instances and RULES of this tycon are loaded
1068 -- Imagine: f :: Double -> Double
1069 tcWiredInTyCon :: TyCon -> IfL TyCon
1070 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1073 tcIfaceClass :: Name -> IfL Class
1074 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1075 ; return (tyThingClass thing) }
1077 tcIfaceDataCon :: Name -> IfL DataCon
1078 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1080 ADataCon dc -> return dc
1081 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1083 tcIfaceExtId :: Name -> IfL Id
1084 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1086 AnId id -> return id
1087 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1090 %************************************************************************
1094 %************************************************************************
1097 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1098 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1099 = do { name <- newIfaceName (mkVarOccFS fs)
1100 ; ty' <- tcIfaceType ty
1101 ; let id = mkLocalId name ty'
1102 ; extendIfaceIdEnv [id] (thing_inside id) }
1103 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1104 = bindIfaceTyVar bndr thing_inside
1106 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1107 bindIfaceBndrs [] thing_inside = thing_inside []
1108 bindIfaceBndrs (b:bs) thing_inside
1109 = bindIfaceBndr b $ \ b' ->
1110 bindIfaceBndrs bs $ \ bs' ->
1111 thing_inside (b':bs')
1113 -----------------------
1114 tcIfaceLetBndr (IfLetBndr fs ty info)
1115 = do { name <- newIfaceName (mkVarOccFS fs)
1116 ; ty' <- tcIfaceType ty
1118 NoInfo -> return (mkLocalId name ty')
1119 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1121 -- Similar to tcIdInfo, but much simpler
1122 tc_info [] = vanillaIdInfo
1123 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1124 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1125 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1126 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1127 (ppr other) (tc_info i)
1129 -----------------------
1130 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1131 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1132 = do { mod <- getIfModule
1133 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1134 ; ty' <- tcIfaceType ty
1135 ; return (mkLocalId name ty') }
1137 -----------------------
1138 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1139 bindIfaceTyVar (occ,kind) thing_inside
1140 = do { name <- newIfaceName (mkTyVarOcc occ)
1141 ; tyvar <- mk_iface_tyvar name kind
1142 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1144 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1145 bindIfaceTyVars bndrs thing_inside
1146 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1147 ; tyvars <- TcRnMonad.zipWithM mk_iface_tyvar names kinds
1148 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1150 (occs,kinds) = unzip bndrs
1152 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1153 mk_iface_tyvar name ifKind
1154 = do { kind <- tcIfaceType ifKind
1155 ; if isCoercionKind kind then
1156 return (Var.mkCoVar name kind)
1158 return (Var.mkTyVar name kind) }