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"
74 An IfaceDecl is populated with RdrNames, and these are not renamed to
75 Names before typechecking, because there should be no scope errors etc.
77 -- For (b) consider: f = $(...h....)
78 -- where h is imported, and calls f via an hi-boot file.
79 -- This is bad! But it is not seen as a staging error, because h
80 -- is indeed imported. We don't want the type-checker to black-hole
81 -- when simplifying and compiling the splice!
83 -- Simple solution: discard any unfolding that mentions a variable
84 -- bound in this module (and hence not yet processed).
85 -- The discarding happens when forkM finds a type error.
87 %************************************************************************
89 %* tcImportDecl is the key function for "faulting in" *
92 %************************************************************************
94 The main idea is this. We are chugging along type-checking source code, and
95 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
96 it in the EPS type envt. So it
98 2 gets the decl for GHC.Base.map
99 3 typechecks it via tcIfaceDecl
100 4 and adds it to the type env in the EPS
102 Note that DURING STEP 4, we may find that map's type mentions a type
103 constructor that also
105 Notice that for imported things we read the current version from the EPS
106 mutable variable. This is important in situations like
108 where the code that e1 expands to might import some defns that
109 also turn out to be needed by the code that e2 expands to.
112 tcImportDecl :: Name -> TcM TyThing
113 -- Entry point for *source-code* uses of importDecl
115 | Just thing <- wiredInNameTyThing_maybe name
116 = do { initIfaceTcRn (loadWiredInHomeIface name)
117 -- See Note [Loading instances] in LoadIface
120 = do { traceIf (text "tcImportDecl" <+> ppr name)
121 ; mb_thing <- initIfaceTcRn (importDecl name)
123 Succeeded thing -> return thing
124 Failed err -> failWithTc err }
126 checkWiredInTyCon :: TyCon -> TcM ()
127 -- Ensure that the home module of the TyCon (and hence its instances)
128 -- are loaded. See See Note [Loading instances] in LoadIface
129 -- It might not be a wired-in tycon (see the calls in TcUnify),
130 -- in which case this is a no-op.
132 | not (isWiredInName tc_name)
135 = do { mod <- getModule
136 ; unless (mod == nameModule tc_name)
137 (initIfaceTcRn (loadWiredInHomeIface tc_name))
138 -- Don't look for (non-existent) Float.hi when
139 -- compiling Float.lhs, which mentions Float of course
140 -- A bit yukky to call initIfaceTcRn here
143 tc_name = tyConName tc
145 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
146 -- Get the TyThing for this Name from an interface file
147 -- It's not a wired-in thing -- the caller caught that
149 = ASSERT( not (isWiredInName name) )
152 -- Load the interface, which should populate the PTE
153 ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
155 Failed err_msg -> return (Failed err_msg) ;
156 Succeeded iface -> do
158 -- Now look it up again; this time we should find it
160 ; case lookupTypeEnv (eps_PTE eps) name of
161 Just thing -> return (Succeeded thing)
162 Nothing -> return (Failed not_found_msg)
165 nd_doc = ptext SLIT("Need decl for") <+> ppr name
166 not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
167 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
168 2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
169 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
172 %************************************************************************
174 Type-checking a complete interface
176 %************************************************************************
178 Suppose we discover we don't need to recompile. Then we must type
179 check the old interface file. This is a bit different to the
180 incremental type checking we do as we suck in interface files. Instead
181 we do things similarly as when we are typechecking source decls: we
182 bring into scope the type envt for the interface all at once, using a
183 knot. Remember, the decls aren't necessarily in dependency order --
184 and even if they were, the type decls might be mutually recursive.
187 typecheckIface :: ModIface -- Get the decls from here
188 -> TcRnIf gbl lcl ModDetails
190 = initIfaceTc iface $ \ tc_env_var -> do
191 -- The tc_env_var is freshly allocated, private to
192 -- type-checking this particular interface
193 { -- Get the right set of decls and rules. If we are compiling without -O
194 -- we discard pragmas before typechecking, so that we don't "see"
195 -- information that we shouldn't. From a versioning point of view
196 -- It's not actually *wrong* to do so, but in fact GHCi is unable
197 -- to handle unboxed tuples, so it must not see unfoldings.
198 ignore_prags <- doptM Opt_IgnoreInterfacePragmas
200 -- Typecheck the decls. This is done lazily, so that the knot-tying
201 -- within this single module work out right. In the If monad there is
202 -- no global envt for the current interface; instead, the knot is tied
203 -- through the if_rec_types field of IfGblEnv
204 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
205 ; let type_env = mkNameEnv names_w_things
206 ; writeMutVar tc_env_var type_env
208 -- Now do those rules and instances
209 ; insts <- mapM tcIfaceInst (mi_insts iface)
210 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
211 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
213 -- Vectorisation information
214 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env
218 ; exports <- ifaceExportNames (mi_exports iface)
221 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
222 text "Type envt:" <+> ppr type_env])
223 ; return $ ModDetails { md_types = type_env
225 , md_fam_insts = fam_insts
227 , md_vect_info = vect_info
228 , md_exports = exports
234 %************************************************************************
236 Type and class declarations
238 %************************************************************************
241 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
242 -- Load the hi-boot iface for the module being compiled,
243 -- if it indeed exists in the transitive closure of imports
244 -- Return the ModDetails, empty if no hi-boot iface
245 tcHiBootIface hsc_src mod
246 | isHsBoot hsc_src -- Already compiling a hs-boot file
247 = return emptyModDetails
249 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
252 ; if not (isOneShot mode)
253 -- In --make and interactive mode, if this module has an hs-boot file
254 -- we'll have compiled it already, and it'll be in the HPT
256 -- We check wheher the interface is a *boot* interface.
257 -- It can happen (when using GHC from Visual Studio) that we
258 -- compile a module in TypecheckOnly mode, with a stable,
259 -- fully-populated HPT. In that case the boot interface isn't there
260 -- (it's been replaced by the mother module) so we can't check it.
261 -- And that's fine, because if M's ModInfo is in the HPT, then
262 -- it's been compiled once, and we don't need to check the boot iface
263 then do { hpt <- getHpt
264 ; case lookupUFM hpt (moduleName mod) of
265 Just info | mi_boot (hm_iface info)
266 -> return (hm_details info)
267 other -> return emptyModDetails }
270 -- OK, so we're in one-shot mode.
271 -- In that case, we're read all the direct imports by now,
272 -- so eps_is_boot will record if any of our imports mention us by
273 -- way of hi-boot file
275 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
276 Nothing -> return emptyModDetails ; -- The typical case
278 Just (_, False) -> failWithTc moduleLoop ;
279 -- Someone below us imported us!
280 -- This is a loop with no hi-boot in the way
282 Just (_mod, True) -> -- There's a hi-boot interface below us
284 do { read_result <- findAndReadIface
288 ; case read_result of
289 Failed err -> failWithTc (elaborate err)
290 Succeeded (iface, _path) -> typecheckIface iface
293 need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
294 <+> ptext SLIT("to compare against the Real Thing")
296 moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
297 <+> ptext SLIT("depends on itself")
299 elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+>
300 quotes (ppr mod) <> colon) 4 err
304 %************************************************************************
306 Type and class declarations
308 %************************************************************************
310 When typechecking a data type decl, we *lazily* (via forkM) typecheck
311 the constructor argument types. This is in the hope that we may never
312 poke on those argument types, and hence may never need to load the
313 interface files for types mentioned in the arg types.
316 data Foo.S = MkS Baz.T
317 Mabye we can get away without even loading the interface for Baz!
319 This is not just a performance thing. Suppose we have
320 data Foo.S = MkS Baz.T
321 data Baz.T = MkT Foo.S
322 (in different interface files, of course).
323 Now, first we load and typecheck Foo.S, and add it to the type envt.
324 If we do explore MkS's argument, we'll load and typecheck Baz.T.
325 If we explore MkT's argument we'll find Foo.S already in the envt.
327 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
328 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
329 which isn't done yet.
331 All very cunning. However, there is a rather subtle gotcha which bit
332 me when developing this stuff. When we typecheck the decl for S, we
333 extend the type envt with S, MkS, and all its implicit Ids. Suppose
334 (a bug, but it happened) that the list of implicit Ids depended in
335 turn on the constructor arg types. Then the following sequence of
337 * we build a thunk <t> for the constructor arg tys
338 * we build a thunk for the extended type environment (depends on <t>)
339 * we write the extended type envt into the global EPS mutvar
341 Now we look something up in the type envt
343 * which reads the global type envt out of the global EPS mutvar
344 * but that depends in turn on <t>
346 It's subtle, because, it'd work fine if we typechecked the constructor args
347 eagerly -- they don't need the extended type envt. They just get the extended
348 type envt by accident, because they look at it later.
350 What this means is that the implicitTyThings MUST NOT DEPEND on any of
355 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
359 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
360 = do { name <- lookupIfaceTop occ_name
361 ; ty <- tcIfaceType iface_type
362 ; info <- tcIdInfo ignore_prags name ty info
363 ; return (AnId (mkVanillaGlobal name ty info)) }
365 tcIfaceDecl ignore_prags
366 (IfaceData {ifName = occ_name,
368 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
371 ifGeneric = want_generic,
372 ifFamInst = mb_family })
373 = do { tc_name <- lookupIfaceTop occ_name
374 ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
376 { tycon <- fixM ( \ tycon -> do
377 { stupid_theta <- tcIfaceCtxt ctxt
380 Nothing -> return Nothing
382 do { famTyCon <- tcIfaceTyCon fam
383 ; insttys <- mapM tcIfaceType tys
384 ; return $ Just (famTyCon, insttys)
386 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
387 ; buildAlgTyCon tc_name tyvars stupid_theta
388 cons is_rec want_generic gadt_syn famInst
390 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
391 ; return (ATyCon tycon)
394 tcIfaceDecl ignore_prags
395 (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs,
396 ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty,
397 ifFamInst = mb_family})
398 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
399 { tc_name <- lookupIfaceTop occ_name
400 ; rhs_tyki <- tcIfaceType rdr_rhs_ty
401 ; let rhs = if isOpen then OpenSynTyCon rhs_tyki Nothing
402 else SynonymTyCon rhs_tyki
403 ; famInst <- case mb_family of
404 Nothing -> return Nothing
406 do { famTyCon <- tcIfaceTyCon fam
407 ; insttys <- mapM tcIfaceType tys
408 ; return $ Just (famTyCon, insttys)
410 ; tycon <- buildSynTyCon tc_name tyvars rhs famInst
411 ; return $ ATyCon tycon
414 tcIfaceDecl ignore_prags
415 (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name,
416 ifTyVars = tv_bndrs, ifFDs = rdr_fds,
417 ifATs = rdr_ats, ifSigs = rdr_sigs,
419 -- ToDo: in hs-boot files we should really treat abstract classes specially,
420 -- as we do abstract tycons
421 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
422 { cls_name <- lookupIfaceTop occ_name
423 ; ctxt <- tcIfaceCtxt rdr_ctxt
424 ; sigs <- mapM tc_sig rdr_sigs
425 ; fds <- mapM tc_fd rdr_fds
426 ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
427 ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
428 ; cls <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
429 ; return (AClass cls) }
431 tc_sig (IfaceClassOp occ dm rdr_ty)
432 = do { op_name <- lookupIfaceTop occ
433 ; op_ty <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
434 -- Must be done lazily for just the same reason as the
435 -- type of a data con; to avoid sucking in types that
436 -- it mentions unless it's necessray to do so
437 ; return (op_name, dm, op_ty) }
439 mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
441 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
442 ; tvs2' <- mapM tcIfaceTyVar tvs2
443 ; return (tvs1', tvs2') }
445 -- For each AT argument compute the position of the corresponding class
446 -- parameter in the class head. This will later serve as a permutation
447 -- vector when checking the validity of instance declarations.
448 setTyThingPoss (ATyCon tycon) atTyVars =
449 let classTyVars = map fst tv_bndrs
451 . map ((`elemIndex` classTyVars) . fst)
453 -- There will be no Nothing, as we already passed renaming
455 ATyCon (setTyConArgPoss tycon poss)
456 setTyThingPoss _ _ = panic "TcIface.setTyThingPoss"
458 tcIfaceDecl ignore_prags (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
459 = do { name <- lookupIfaceTop rdr_name
460 ; return (ATyCon (mkForeignTyCon name ext_name
463 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
465 IfAbstractTyCon -> return mkAbstractTyConRhs
466 IfOpenDataTyCon -> return mkOpenDataTyConRhs
467 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
468 ; return (mkDataTyConRhs data_cons) }
469 IfNewTyCon con -> do { data_con <- tc_con_decl con
470 ; mkNewTyConRhs tycon_name tycon data_con }
472 tc_con_decl (IfCon { ifConInfix = is_infix,
473 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
474 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
475 ifConArgTys = args, ifConFields = field_lbls,
476 ifConStricts = stricts})
477 = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
478 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
479 { name <- lookupIfaceTop occ
480 ; eq_spec <- tcIfaceEqSpec spec
481 ; theta <- tcIfaceCtxt ctxt -- Laziness seems not worth the bother here
482 -- At one stage I thought that this context checking *had*
483 -- to be lazy, because of possible mutual recursion between the
484 -- type and the classe:
486 -- class Real a where { toRat :: a -> Ratio Integer }
487 -- data (Real a) => Ratio a = ...
488 -- But now I think that the laziness in checking class ops breaks
489 -- the loop, so no laziness needed
491 -- Read the argument types, but lazily to avoid faulting in
492 -- the component types unless they are really needed
493 ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
494 ; lbl_names <- mapM lookupIfaceTop field_lbls
496 ; buildDataCon name is_infix {- Not infix -}
498 univ_tyvars ex_tyvars
502 mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
507 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
508 ; ty <- tcIfaceType if_ty
513 %************************************************************************
517 %************************************************************************
520 tcIfaceInst :: IfaceInst -> IfL Instance
521 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
522 ifInstCls = cls, ifInstTys = mb_tcs,
524 = do { dfun <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
525 tcIfaceExtId dfun_occ
526 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
527 ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
529 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
530 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon,
531 ifFamInstFam = fam, ifFamInstTys = mb_tcs })
532 -- { tycon' <- forkM (ptext SLIT("Inst tycon") <+> ppr tycon) $
533 -- ^^^this line doesn't work, but vvv this does => CPP in Haskell = evil!
534 = do tycon' <- forkM (text ("Inst tycon") <+> ppr tycon) $
536 let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
537 return (mkImportedFamInst fam mb_tcs' tycon')
541 %************************************************************************
545 %************************************************************************
547 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
548 are in the type environment. However, remember that typechecking a Rule may
549 (as a side effect) augment the type envt, and so we may need to iterate the process.
552 tcIfaceRules :: Bool -- True <=> ignore rules
555 tcIfaceRules ignore_prags if_rules
556 | ignore_prags = return []
557 | otherwise = mapM tcIfaceRule if_rules
559 tcIfaceRule :: IfaceRule -> IfL CoreRule
560 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
561 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
563 = do { ~(bndrs', args', rhs') <-
564 -- Typecheck the payload lazily, in the hope it'll never be looked at
565 forkM (ptext SLIT("Rule") <+> ftext name) $
566 bindIfaceBndrs bndrs $ \ bndrs' ->
567 do { args' <- mapM tcIfaceExpr args
568 ; rhs' <- tcIfaceExpr rhs
569 ; return (bndrs', args', rhs') }
570 ; let mb_tcs = map ifTopFreeName args
571 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
572 ru_bndrs = bndrs', ru_args = args',
575 ru_local = False }) } -- An imported RULE is never for a local Id
576 -- or, even if it is (module loop, perhaps)
577 -- we'll just leave it in the non-local set
579 -- This function *must* mirror exactly what Rules.topFreeName does
580 -- We could have stored the ru_rough field in the iface file
581 -- but that would be redundant, I think.
582 -- The only wrinkle is that we must not be deceived by
583 -- type syononyms at the top of a type arg. Since
584 -- we can't tell at this point, we are careful not
585 -- to write them out in coreRuleToIfaceRule
586 ifTopFreeName :: IfaceExpr -> Maybe Name
587 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
588 ifTopFreeName (IfaceApp f a) = ifTopFreeName f
589 ifTopFreeName (IfaceExt n) = Just n
590 ifTopFreeName other = Nothing
594 %************************************************************************
596 Vectorisation information
598 %************************************************************************
601 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
602 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
603 { ifaceVectInfoVar = vars
604 , ifaceVectInfoTyCon = tycons
605 , ifaceVectInfoTyConReuse = tyconsReuse
607 = do { vVars <- mapM vectVarMapping vars
608 ; tyConRes1 <- mapM vectTyConMapping tycons
609 ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
610 ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
612 { vectInfoVar = mkVarEnv vVars
613 , vectInfoTyCon = mkNameEnv vTyCons
614 , vectInfoDataCon = mkNameEnv (concat vDataCons)
615 , vectInfoPADFun = mkNameEnv vPAs
616 , vectInfoIso = mkNameEnv vIsos
621 = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
622 ; let { var = lookupVar name
623 ; vVar = lookupVar vName
625 ; return (var, (var, vVar))
627 vectTyConMapping name
628 = do { vName <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
629 ; paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
630 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
631 ; let { tycon = lookupTyCon name
632 ; vTycon = lookupTyCon vName
633 ; paTycon = lookupVar paName
634 ; isoTycon = lookupVar isoName
636 ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
637 ; return ((name, (tycon, vTycon)), -- (T, T_v)
638 vDataCons, -- list of (Ci, Ci_v)
639 (vName, (vTycon, paTycon)), -- (T_v, paT)
640 (name, (tycon, isoTycon))) -- (T, isoT)
642 vectTyConReuseMapping name
643 = do { paName <- lookupOrig mod (mkPADFunOcc (nameOccName name))
644 ; isoName <- lookupOrig mod (mkVectIsoOcc (nameOccName name))
645 ; let { tycon = lookupTyCon name
646 ; paTycon = lookupVar paName
647 ; isoTycon = lookupVar isoName
648 ; vDataCons = [ (dataConName dc, (dc, dc))
649 | dc <- tyConDataCons tycon]
651 ; return ((name, (tycon, tycon)), -- (T, T)
652 vDataCons, -- list of (Ci, Ci)
653 (name, (tycon, paTycon)), -- (T, paT)
654 (name, (tycon, isoTycon))) -- (T, isoT)
656 vectDataConMapping datacon
657 = do { let name = dataConName datacon
658 ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
659 ; let vDataCon = lookupDataCon vName
660 ; return (name, (datacon, vDataCon))
663 lookupVar name = case lookupTypeEnv typeEnv name of
664 Just (AnId var) -> var
666 panic "TcIface.tcIfaceVectInfo: not an id"
668 panic "TcIface.tcIfaceVectInfo: unknown name"
669 lookupTyCon name = case lookupTypeEnv typeEnv name of
670 Just (ATyCon tc) -> tc
672 panic "TcIface.tcIfaceVectInfo: not a tycon"
674 panic "TcIface.tcIfaceVectInfo: unknown name"
675 lookupDataCon name = case lookupTypeEnv typeEnv name of
676 Just (ADataCon dc) -> dc
678 panic "TcIface.tcIfaceVectInfo: not a datacon"
680 panic "TcIface.tcIfaceVectInfo: unknown name"
683 %************************************************************************
687 %************************************************************************
690 tcIfaceType :: IfaceType -> IfL Type
691 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
692 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
693 tcIfaceType (IfaceFunTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
694 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
695 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
696 tcIfaceType (IfacePredTy st) = do { st' <- tcIfacePredType st; return (PredTy st') }
698 tcIfaceTypes tys = mapM tcIfaceType tys
700 -----------------------------------------
701 tcIfacePredType :: IfacePredType -> IfL PredType
702 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
703 tcIfacePredType (IfaceIParam ip t) = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
704 tcIfacePredType (IfaceEqPred t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
706 -----------------------------------------
707 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
708 tcIfaceCtxt sts = mapM tcIfacePredType sts
712 %************************************************************************
716 %************************************************************************
719 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
720 tcIfaceExpr (IfaceType ty)
721 = Type <$> tcIfaceType ty
723 tcIfaceExpr (IfaceLcl name)
724 = Var <$> tcIfaceLclId name
726 tcIfaceExpr (IfaceTick modName tickNo)
727 = Var <$> tcIfaceTick modName tickNo
729 tcIfaceExpr (IfaceExt gbl)
730 = Var <$> tcIfaceExtId gbl
732 tcIfaceExpr (IfaceLit lit)
735 tcIfaceExpr (IfaceFCall cc ty) = do
736 ty' <- tcIfaceType ty
738 return (Var (mkFCallId u cc ty'))
740 tcIfaceExpr (IfaceTuple boxity args) = do
741 args' <- mapM tcIfaceExpr args
742 -- Put the missing type arguments back in
743 let con_args = map (Type . exprType) args' ++ args'
744 return (mkApps (Var con_id) con_args)
747 con_id = dataConWorkId (tupleCon boxity arity)
750 tcIfaceExpr (IfaceLam bndr body)
751 = bindIfaceBndr bndr $ \bndr' ->
752 Lam bndr' <$> tcIfaceExpr body
754 tcIfaceExpr (IfaceApp fun arg)
755 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
757 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) = do
758 scrut' <- tcIfaceExpr scrut
759 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
761 scrut_ty = exprType scrut'
762 case_bndr' = mkLocalId case_bndr_name scrut_ty
763 tc_app = splitTyConApp scrut_ty
764 -- NB: Won't always succeed (polymoprhic case)
765 -- but won't be demanded in those cases
766 -- NB: not tcSplitTyConApp; we are looking at Core here
767 -- look through non-rec newtypes to find the tycon that
768 -- corresponds to the datacon in this case alternative
770 extendIfaceIdEnv [case_bndr'] $ do
771 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
772 ty' <- tcIfaceType ty
773 return (Case scrut' case_bndr' ty' alts')
775 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
776 rhs' <- tcIfaceExpr rhs
777 id <- tcIfaceLetBndr bndr
778 body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
779 return (Let (NonRec id rhs') body')
781 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
782 ids <- mapM tcIfaceLetBndr bndrs
783 extendIfaceIdEnv ids $ do
784 rhss' <- mapM tcIfaceExpr rhss
785 body' <- tcIfaceExpr body
786 return (Let (Rec (ids `zip` rhss')) body')
788 (bndrs, rhss) = unzip pairs
790 tcIfaceExpr (IfaceCast expr co) = do
791 expr' <- tcIfaceExpr expr
792 co' <- tcIfaceType co
793 return (Cast expr' co')
795 tcIfaceExpr (IfaceNote note expr) = do
796 expr' <- tcIfaceExpr expr
798 IfaceInlineMe -> return (Note InlineMe expr')
799 IfaceSCC cc -> return (Note (SCC cc) expr')
800 IfaceCoreNote n -> return (Note (CoreNote n) expr')
802 -------------------------
803 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
804 = ASSERT( null names ) do
805 rhs' <- tcIfaceExpr rhs
806 return (DEFAULT, [], rhs')
808 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
809 = ASSERT( null names ) do
810 rhs' <- tcIfaceExpr rhs
811 return (LitAlt lit, [], rhs')
813 -- A case alternative is made quite a bit more complicated
814 -- by the fact that we omit type annotations because we can
815 -- work them out. True enough, but its not that easy!
816 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
817 = do { con <- tcIfaceDataCon data_occ
818 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
819 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
820 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
822 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
823 = ASSERT( isTupleTyCon tycon )
824 do { let [data_con] = tyConDataCons tycon
825 ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
827 tcIfaceDataAlt con inst_tys arg_strs rhs
828 = do { us <- newUniqueSupply
829 ; let uniqs = uniqsFromSupply us
830 ; let (ex_tvs, co_tvs, arg_ids)
831 = dataConRepFSInstPat arg_strs uniqs con inst_tys
832 all_tvs = ex_tvs ++ co_tvs
834 ; rhs' <- extendIfaceTyVarEnv all_tvs $
835 extendIfaceIdEnv arg_ids $
837 ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
842 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind] -- Used for external core
843 tcExtCoreBindings [] = return []
844 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
846 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
847 do_one (IfaceNonRec bndr rhs) thing_inside
848 = do { rhs' <- tcIfaceExpr rhs
849 ; bndr' <- newExtCoreBndr bndr
850 ; extendIfaceIdEnv [bndr'] $ do
851 { core_binds <- thing_inside
852 ; return (NonRec bndr' rhs' : core_binds) }}
854 do_one (IfaceRec pairs) thing_inside
855 = do { bndrs' <- mapM newExtCoreBndr bndrs
856 ; extendIfaceIdEnv bndrs' $ do
857 { rhss' <- mapM tcIfaceExpr rhss
858 ; core_binds <- thing_inside
859 ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
861 (bndrs,rhss) = unzip pairs
865 %************************************************************************
869 %************************************************************************
872 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
873 tcIdInfo ignore_prags name ty info
874 | ignore_prags = return vanillaIdInfo
875 | otherwise = case info of
876 NoInfo -> return vanillaIdInfo
877 HasInfo info -> foldlM tcPrag init_info info
879 -- Set the CgInfo to something sensible but uninformative before
880 -- we start; default assumption is that it has CAFs
881 init_info = vanillaIdInfo
883 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
884 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
885 tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
887 -- The next two are lazy, so they don't transitively suck stuff in
888 tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
889 tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
890 tcPrag info (HsUnfold expr) = do
891 maybe_expr' <- tcPragExpr name expr
893 -- maybe_expr' doesn't get looked at if the unfolding
894 -- is never inspected; so the typecheck doesn't even happen
895 unfold_info = case maybe_expr' of
896 Nothing -> noUnfolding
897 Just expr' -> mkTopUnfolding expr'
898 return (info `setUnfoldingInfoLazily` unfold_info)
902 tcWorkerInfo ty info wkr arity
903 = do { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
905 -- We return without testing maybe_wkr_id, but as soon as info is
906 -- looked at we will test it. That's ok, because its outside the
907 -- knot; and there seems no big reason to further defer the
908 -- tcIfaceId lookup. (Contrast with tcPragExpr, where postponing walking
909 -- over the unfolding until it's actually used does seem worth while.)
910 ; us <- newUniqueSupply
912 ; return (case mb_wkr_id of
914 Just wkr_id -> add_wkr_info us wkr_id info) }
916 doc = text "Worker for" <+> ppr wkr
917 add_wkr_info us wkr_id info
918 = info `setUnfoldingInfoLazily` mk_unfolding us wkr_id
919 `setWorkerInfo` HasWorker wkr_id arity
921 mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
923 -- We are relying here on strictness info always appearing
924 -- before worker info, fingers crossed ....
925 strict_sig = case newStrictnessInfo info of
927 Nothing -> pprPanic "Worker info but no strictness for" (ppr wkr)
930 For unfoldings we try to do the job lazily, so that we never type check
931 an unfolding that isn't going to be looked at.
934 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
936 = forkM_maybe doc $ do
937 core_expr' <- tcIfaceExpr expr
939 -- Check for type consistency in the unfolding
940 ifOptM Opt_DoCoreLinting $ do
941 in_scope <- get_in_scope_ids
942 case lintUnfolding noSrcLoc in_scope core_expr' of
944 Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
948 doc = text "Unfolding of" <+> ppr name
949 get_in_scope_ids -- Urgh; but just for linting
951 do { env <- getGblEnv
952 ; case if_rec_types env of {
953 Nothing -> return [] ;
954 Just (_, get_env) -> do
955 { type_env <- get_env
956 ; return (typeEnvIds type_env) }}}
961 %************************************************************************
963 Getting from Names to TyThings
965 %************************************************************************
968 tcIfaceGlobal :: Name -> IfL TyThing
970 | Just thing <- wiredInNameTyThing_maybe name
971 -- Wired-in things include TyCons, DataCons, and Ids
972 = do { ifCheckWiredInThing name; return thing }
974 = do { env <- getGblEnv
975 ; case if_rec_types env of { -- Note [Tying the knot]
976 Just (mod, get_type_env)
977 | nameIsLocalOrFrom mod name
978 -> do -- It's defined in the module being compiled
979 { type_env <- setLclEnv () get_type_env -- yuk
980 ; case lookupNameEnv type_env name of
981 Just thing -> return thing
982 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
983 (ppr name $$ ppr type_env) }
987 { (eps,hpt) <- getEpsAndHpt
989 ; case lookupType dflags hpt (eps_PTE eps) name of {
990 Just thing -> return thing ;
993 { mb_thing <- importDecl name -- It's imported; go get it
995 Failed err -> failIfM err
996 Succeeded thing -> return thing
999 -- Note [Tying the knot]
1000 -- ~~~~~~~~~~~~~~~~~~~~~
1001 -- The if_rec_types field is used in two situations:
1003 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1004 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1005 -- after we've built M's type envt.
1007 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1008 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1009 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1011 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1012 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1013 -- emasculated form (e.g. lacking data constructors).
1015 ifCheckWiredInThing :: Name -> IfL ()
1016 -- Even though we are in an interface file, we want to make
1017 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1018 -- Ditto want to ensure that RULES are loaded too
1019 -- See Note [Loading instances] in LoadIface
1020 ifCheckWiredInThing name
1021 = do { mod <- getIfModule
1022 -- Check whether we are typechecking the interface for this
1023 -- very module. E.g when compiling the base library in --make mode
1024 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1025 -- the HPT, so without the test we'll demand-load it into the PIT!
1026 -- C.f. the same test in checkWiredInTyCon above
1027 ; unless (mod == nameModule name)
1028 (loadWiredInHomeIface name) }
1030 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1031 tcIfaceTyCon IfaceIntTc = tcWiredInTyCon intTyCon
1032 tcIfaceTyCon IfaceBoolTc = tcWiredInTyCon boolTyCon
1033 tcIfaceTyCon IfaceCharTc = tcWiredInTyCon charTyCon
1034 tcIfaceTyCon IfaceListTc = tcWiredInTyCon listTyCon
1035 tcIfaceTyCon IfacePArrTc = tcWiredInTyCon parrTyCon
1036 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1037 tcIfaceTyCon (IfaceTc name) = do { thing <- tcIfaceGlobal name
1038 ; return (check_tc (tyThingTyCon thing)) }
1041 | debugIsOn = case toIfaceTyCon tc of
1043 other -> pprTrace "check_tc" (ppr tc) tc
1045 -- we should be okay just returning Kind constructors without extra loading
1046 tcIfaceTyCon IfaceLiftedTypeKindTc = return liftedTypeKindTyCon
1047 tcIfaceTyCon IfaceOpenTypeKindTc = return openTypeKindTyCon
1048 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1049 tcIfaceTyCon IfaceArgTypeKindTc = return argTypeKindTyCon
1050 tcIfaceTyCon IfaceUbxTupleKindTc = return ubxTupleKindTyCon
1052 -- Even though we are in an interface file, we want to make
1053 -- sure the instances and RULES of this tycon are loaded
1054 -- Imagine: f :: Double -> Double
1055 tcWiredInTyCon :: TyCon -> IfL TyCon
1056 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1059 tcIfaceClass :: Name -> IfL Class
1060 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1061 ; return (tyThingClass thing) }
1063 tcIfaceDataCon :: Name -> IfL DataCon
1064 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1066 ADataCon dc -> return dc
1067 other -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1069 tcIfaceExtId :: Name -> IfL Id
1070 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1072 AnId id -> return id
1073 other -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1076 %************************************************************************
1080 %************************************************************************
1083 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1084 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1085 = do { name <- newIfaceName (mkVarOccFS fs)
1086 ; ty' <- tcIfaceType ty
1087 ; let id = mkLocalId name ty'
1088 ; extendIfaceIdEnv [id] (thing_inside id) }
1089 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1090 = bindIfaceTyVar bndr thing_inside
1092 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1093 bindIfaceBndrs [] thing_inside = thing_inside []
1094 bindIfaceBndrs (b:bs) thing_inside
1095 = bindIfaceBndr b $ \ b' ->
1096 bindIfaceBndrs bs $ \ bs' ->
1097 thing_inside (b':bs')
1099 -----------------------
1100 tcIfaceLetBndr (IfLetBndr fs ty info)
1101 = do { name <- newIfaceName (mkVarOccFS fs)
1102 ; ty' <- tcIfaceType ty
1104 NoInfo -> return (mkLocalId name ty')
1105 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) }
1107 -- Similar to tcIdInfo, but much simpler
1108 tc_info [] = vanillaIdInfo
1109 tc_info (HsInline p : i) = tc_info i `setInlinePragInfo` p
1110 tc_info (HsArity a : i) = tc_info i `setArityInfo` a
1111 tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s
1112 tc_info (other : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo"
1113 (ppr other) (tc_info i)
1115 -----------------------
1116 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1117 newExtCoreBndr (IfLetBndr var ty _) -- Ignoring IdInfo for now
1118 = do { mod <- getIfModule
1119 ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1120 ; ty' <- tcIfaceType ty
1121 ; return (mkLocalId name ty') }
1123 -----------------------
1124 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1125 bindIfaceTyVar (occ,kind) thing_inside
1126 = do { name <- newIfaceName (mkTyVarOcc occ)
1127 ; tyvar <- mk_iface_tyvar name kind
1128 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1130 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1131 bindIfaceTyVars bndrs thing_inside
1132 = do { names <- newIfaceNames (map mkTyVarOcc occs)
1133 ; tyvars <- zipWithM mk_iface_tyvar names kinds
1134 ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1136 (occs,kinds) = unzip bndrs
1138 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1139 mk_iface_tyvar name ifKind
1140 = do { kind <- tcIfaceType ifKind
1141 ; if isCoercionKind kind then
1142 return (Var.mkCoVar name kind)
1144 return (Var.mkTyVar name kind) }