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