Refactor self-boot info
[ghc.git] / compiler / iface / TcIface.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Type checking of type signatures in interface files
7 -}
8
9 {-# LANGUAGE CPP #-}
10
11 module TcIface (
12 tcLookupImported_maybe,
13 importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
14 tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
15 tcIfaceVectInfo, tcIfaceAnnotations,
16 tcIfaceExpr, -- Desired by HERMIT (Trac #7683)
17 tcIfaceGlobal
18 ) where
19
20 #include "HsVersions.h"
21
22 import TcTypeNats(typeNatCoAxiomRules)
23 import IfaceSyn
24 import LoadIface
25 import IfaceEnv
26 import BuildTyCl
27 import TcRnMonad
28 import TcType
29 import Type
30 import Coercion hiding (substTy)
31 import TypeRep
32 import HscTypes
33 import Annotations
34 import InstEnv
35 import FamInstEnv
36 import CoreSyn
37 import CoreUtils
38 import CoreUnfold
39 import CoreLint
40 import MkCore
41 import Id
42 import MkId
43 import IdInfo
44 import Class
45 import TyCon
46 import CoAxiom
47 import ConLike
48 import DataCon
49 import PrelNames
50 import TysWiredIn
51 import TysPrim ( superKindTyConName )
52 import BasicTypes ( strongLoopBreaker, Arity, TupleSort(..), Boxity(..) )
53 import Literal
54 import qualified Var
55 import VarEnv
56 import VarSet
57 import Name
58 import NameEnv
59 import NameSet
60 import OccurAnal ( occurAnalyseExpr )
61 import Demand
62 import Module
63 import UniqFM
64 import UniqSupply
65 import Outputable
66 import Maybes
67 import SrcLoc
68 import DynFlags
69 import Util
70 import FastString
71
72 import Control.Monad
73 import qualified Data.Map as Map
74 #if __GLASGOW_HASKELL__ < 709
75 import Data.Traversable ( traverse )
76 #endif
77
78 {-
79 This module takes
80
81 IfaceDecl -> TyThing
82 IfaceType -> Type
83 etc
84
85 An IfaceDecl is populated with RdrNames, and these are not renamed to
86 Names before typechecking, because there should be no scope errors etc.
87
88 -- For (b) consider: f = \$(...h....)
89 -- where h is imported, and calls f via an hi-boot file.
90 -- This is bad! But it is not seen as a staging error, because h
91 -- is indeed imported. We don't want the type-checker to black-hole
92 -- when simplifying and compiling the splice!
93 --
94 -- Simple solution: discard any unfolding that mentions a variable
95 -- bound in this module (and hence not yet processed).
96 -- The discarding happens when forkM finds a type error.
97
98
99 ************************************************************************
100 * *
101 Type-checking a complete interface
102 * *
103 ************************************************************************
104
105 Suppose we discover we don't need to recompile. Then we must type
106 check the old interface file. This is a bit different to the
107 incremental type checking we do as we suck in interface files. Instead
108 we do things similarly as when we are typechecking source decls: we
109 bring into scope the type envt for the interface all at once, using a
110 knot. Remember, the decls aren't necessarily in dependency order --
111 and even if they were, the type decls might be mutually recursive.
112 -}
113
114 typecheckIface :: ModIface -- Get the decls from here
115 -> TcRnIf gbl lcl ModDetails
116 typecheckIface iface
117 = initIfaceTc iface $ \ tc_env_var -> do
118 -- The tc_env_var is freshly allocated, private to
119 -- type-checking this particular interface
120 { -- Get the right set of decls and rules. If we are compiling without -O
121 -- we discard pragmas before typechecking, so that we don't "see"
122 -- information that we shouldn't. From a versioning point of view
123 -- It's not actually *wrong* to do so, but in fact GHCi is unable
124 -- to handle unboxed tuples, so it must not see unfoldings.
125 ignore_prags <- goptM Opt_IgnoreInterfacePragmas
126
127 -- Typecheck the decls. This is done lazily, so that the knot-tying
128 -- within this single module work out right. In the If monad there is
129 -- no global envt for the current interface; instead, the knot is tied
130 -- through the if_rec_types field of IfGblEnv
131 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
132 ; let type_env = mkNameEnv names_w_things
133 ; writeMutVar tc_env_var type_env
134
135 -- Now do those rules, instances and annotations
136 ; insts <- mapM tcIfaceInst (mi_insts iface)
137 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
138 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
139 ; anns <- tcIfaceAnnotations (mi_anns iface)
140
141 -- Vectorisation information
142 ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env (mi_vect_info iface)
143
144 -- Exports
145 ; exports <- ifaceExportNames (mi_exports iface)
146
147 -- Finished
148 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
149 text "Type envt:" <+> ppr type_env])
150 ; return $ ModDetails { md_types = type_env
151 , md_insts = insts
152 , md_fam_insts = fam_insts
153 , md_rules = rules
154 , md_anns = anns
155 , md_vect_info = vect_info
156 , md_exports = exports
157 }
158 }
159
160 {-
161 ************************************************************************
162 * *
163 Type and class declarations
164 * *
165 ************************************************************************
166 -}
167
168 tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
169 -- Load the hi-boot iface for the module being compiled,
170 -- if it indeed exists in the transitive closure of imports
171 -- Return the ModDetails; Nothing if no hi-boot iface
172 tcHiBootIface hsc_src mod
173 | HsBootFile <- hsc_src -- Already compiling a hs-boot file
174 = return NoSelfBoot
175 | otherwise
176 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
177
178 ; mode <- getGhcMode
179 ; if not (isOneShot mode)
180 -- In --make and interactive mode, if this module has an hs-boot file
181 -- we'll have compiled it already, and it'll be in the HPT
182 --
183 -- We check wheher the interface is a *boot* interface.
184 -- It can happen (when using GHC from Visual Studio) that we
185 -- compile a module in TypecheckOnly mode, with a stable,
186 -- fully-populated HPT. In that case the boot interface isn't there
187 -- (it's been replaced by the mother module) so we can't check it.
188 -- And that's fine, because if M's ModInfo is in the HPT, then
189 -- it's been compiled once, and we don't need to check the boot iface
190 then do { hpt <- getHpt
191 ; case lookupUFM hpt (moduleName mod) of
192 Just info | mi_boot (hm_iface info)
193 -> return (mkSelfBootInfo (hm_details info))
194 _ -> return NoSelfBoot }
195 else do
196
197 -- OK, so we're in one-shot mode.
198 -- Re #9245, we always check if there is an hi-boot interface
199 -- to check consistency against, rather than just when we notice
200 -- that an hi-boot is necessary due to a circular import.
201 { read_result <- findAndReadIface
202 need mod
203 True -- Hi-boot file
204
205 ; case read_result of {
206 Succeeded (iface, _path) -> do { tc_iface <- typecheckIface iface
207 ; return (mkSelfBootInfo tc_iface) } ;
208 Failed err ->
209
210 -- There was no hi-boot file. But if there is circularity in
211 -- the module graph, there really should have been one.
212 -- Since we've read all the direct imports by now,
213 -- eps_is_boot will record if any of our imports mention the
214 -- current module, which either means a module loop (not
215 -- a SOURCE import) or that our hi-boot file has mysteriously
216 -- disappeared.
217 do { eps <- getEps
218 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of
219 Nothing -> return NoSelfBoot -- The typical case
220
221 Just (_, False) -> failWithTc moduleLoop
222 -- Someone below us imported us!
223 -- This is a loop with no hi-boot in the way
224
225 Just (_mod, True) -> failWithTc (elaborate err)
226 -- The hi-boot file has mysteriously disappeared.
227 }}}}
228 where
229 need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
230 <+> ptext (sLit "to compare against the Real Thing")
231
232 moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod)
233 <+> ptext (sLit "depends on itself")
234
235 elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+>
236 quotes (ppr mod) <> colon) 4 err
237
238
239 mkSelfBootInfo :: ModDetails -> SelfBootInfo
240 mkSelfBootInfo mds
241 = SelfBoot { sb_mds = mds
242 , sb_tcs = mkNameSet (map tyConName (typeEnvTyCons iface_env))
243 , sb_ids = mkNameSet (map idName (typeEnvIds iface_env)) }
244 where
245 iface_env = md_types mds
246
247 {-
248 ************************************************************************
249 * *
250 Type and class declarations
251 * *
252 ************************************************************************
253
254 When typechecking a data type decl, we *lazily* (via forkM) typecheck
255 the constructor argument types. This is in the hope that we may never
256 poke on those argument types, and hence may never need to load the
257 interface files for types mentioned in the arg types.
258
259 E.g.
260 data Foo.S = MkS Baz.T
261 Mabye we can get away without even loading the interface for Baz!
262
263 This is not just a performance thing. Suppose we have
264 data Foo.S = MkS Baz.T
265 data Baz.T = MkT Foo.S
266 (in different interface files, of course).
267 Now, first we load and typecheck Foo.S, and add it to the type envt.
268 If we do explore MkS's argument, we'll load and typecheck Baz.T.
269 If we explore MkT's argument we'll find Foo.S already in the envt.
270
271 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
272 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
273 which isn't done yet.
274
275 All very cunning. However, there is a rather subtle gotcha which bit
276 me when developing this stuff. When we typecheck the decl for S, we
277 extend the type envt with S, MkS, and all its implicit Ids. Suppose
278 (a bug, but it happened) that the list of implicit Ids depended in
279 turn on the constructor arg types. Then the following sequence of
280 events takes place:
281 * we build a thunk <t> for the constructor arg tys
282 * we build a thunk for the extended type environment (depends on <t>)
283 * we write the extended type envt into the global EPS mutvar
284
285 Now we look something up in the type envt
286 * that pulls on <t>
287 * which reads the global type envt out of the global EPS mutvar
288 * but that depends in turn on <t>
289
290 It's subtle, because, it'd work fine if we typechecked the constructor args
291 eagerly -- they don't need the extended type envt. They just get the extended
292 type envt by accident, because they look at it later.
293
294 What this means is that the implicitTyThings MUST NOT DEPEND on any of
295 the forkM stuff.
296 -}
297
298 tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
299 -> IfaceDecl
300 -> IfL TyThing
301 tcIfaceDecl = tc_iface_decl NoParentTyCon
302
303 tc_iface_decl :: TyConParent -- For nested declarations
304 -> Bool -- True <=> discard IdInfo on IfaceId bindings
305 -> IfaceDecl
306 -> IfL TyThing
307 tc_iface_decl _ ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type,
308 ifIdDetails = details, ifIdInfo = info})
309 = do { name <- lookupIfaceTop occ_name
310 ; ty <- tcIfaceType iface_type
311 ; details <- tcIdDetails ty details
312 ; info <- tcIdInfo ignore_prags name ty info
313 ; return (AnId (mkGlobalId details name ty info)) }
314
315 tc_iface_decl parent _ (IfaceData {ifName = occ_name,
316 ifCType = cType,
317 ifTyVars = tv_bndrs,
318 ifRoles = roles,
319 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
320 ifCons = rdr_cons,
321 ifRec = is_rec, ifPromotable = is_prom,
322 ifParent = mb_parent })
323 = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
324 { tc_name <- lookupIfaceTop occ_name
325 ; tycon <- fixM $ \ tycon -> do
326 { stupid_theta <- tcIfaceCtxt ctxt
327 ; parent' <- tc_parent mb_parent
328 ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
329 ; return (buildAlgTyCon tc_name tyvars roles cType stupid_theta
330 cons is_rec is_prom gadt_syn parent') }
331 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
332 ; return (ATyCon tycon) }
333 where
334 tc_parent :: IfaceTyConParent -> IfL TyConParent
335 tc_parent IfNoParent = return parent
336 tc_parent (IfDataInstance ax_name _ arg_tys)
337 = ASSERT( isNoParent parent )
338 do { ax <- tcIfaceCoAxiom ax_name
339 ; let fam_tc = coAxiomTyCon ax
340 ax_unbr = toUnbranchedAxiom ax
341 ; lhs_tys <- tcIfaceTcArgs arg_tys
342 ; return (FamInstTyCon ax_unbr fam_tc lhs_tys) }
343
344 tc_iface_decl _ _ (IfaceSynonym {ifName = occ_name, ifTyVars = tv_bndrs,
345 ifRoles = roles,
346 ifSynRhs = rhs_ty,
347 ifSynKind = kind })
348 = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
349 { tc_name <- lookupIfaceTop occ_name
350 ; rhs_kind <- tcIfaceKind kind -- Note [Synonym kind loop]
351 ; rhs <- forkM (mk_doc tc_name) $
352 tcIfaceType rhs_ty
353 ; tycon <- buildSynonymTyCon tc_name tyvars roles rhs rhs_kind
354 ; return (ATyCon tycon) }
355 where
356 mk_doc n = ptext (sLit "Type synonym") <+> ppr n
357
358 tc_iface_decl parent _ (IfaceFamily {ifName = occ_name, ifTyVars = tv_bndrs,
359 ifFamFlav = fam_flav,
360 ifFamKind = kind })
361 = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
362 { tc_name <- lookupIfaceTop occ_name
363 ; rhs_kind <- tcIfaceKind kind -- Note [Synonym kind loop]
364 ; rhs <- forkM (mk_doc tc_name) $
365 tc_fam_flav fam_flav
366 ; tycon <- buildFamilyTyCon tc_name tyvars rhs rhs_kind parent
367 ; return (ATyCon tycon) }
368 where
369 mk_doc n = ptext (sLit "Type synonym") <+> ppr n
370 tc_fam_flav IfaceOpenSynFamilyTyCon = return OpenSynFamilyTyCon
371 tc_fam_flav (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
372 = do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
373 ; return (ClosedSynFamilyTyCon ax) }
374 tc_fam_flav IfaceAbstractClosedSynFamilyTyCon
375 = return AbstractClosedSynFamilyTyCon
376 tc_fam_flav IfaceBuiltInSynFamTyCon
377 = pprPanic "tc_iface_decl"
378 (text "IfaceBuiltInSynFamTyCon in interface file")
379
380 tc_iface_decl _parent ignore_prags
381 (IfaceClass {ifCtxt = rdr_ctxt, ifName = tc_occ,
382 ifTyVars = tv_bndrs, ifRoles = roles, ifFDs = rdr_fds,
383 ifATs = rdr_ats, ifSigs = rdr_sigs,
384 ifMinDef = mindef_occ, ifRec = tc_isrec })
385 -- ToDo: in hs-boot files we should really treat abstract classes specially,
386 -- as we do abstract tycons
387 = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
388 { tc_name <- lookupIfaceTop tc_occ
389 ; traceIf (text "tc-iface-class1" <+> ppr tc_occ)
390 ; ctxt <- mapM tc_sc rdr_ctxt
391 ; traceIf (text "tc-iface-class2" <+> ppr tc_occ)
392 ; sigs <- mapM tc_sig rdr_sigs
393 ; fds <- mapM tc_fd rdr_fds
394 ; traceIf (text "tc-iface-class3" <+> ppr tc_occ)
395 ; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
396 ; cls <- fixM $ \ cls -> do
397 { ats <- mapM (tc_at cls) rdr_ats
398 ; traceIf (text "tc-iface-class4" <+> ppr tc_occ)
399 ; buildClass tc_name tyvars roles ctxt fds ats sigs mindef tc_isrec }
400 ; return (ATyCon (classTyCon cls)) }
401 where
402 tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
403 -- The *length* of the superclasses is used by buildClass, and hence must
404 -- not be inside the thunk. But the *content* maybe recursive and hence
405 -- must be lazy (via forkM). Example:
406 -- class C (T a) => D a where
407 -- data T a
408 -- Here the associated type T is knot-tied with the class, and
409 -- so we must not pull on T too eagerly. See Trac #5970
410
411 tc_sig (IfaceClassOp occ dm rdr_ty)
412 = do { op_name <- lookupIfaceTop occ
413 ; op_ty <- forkM (mk_op_doc op_name rdr_ty) (tcIfaceType rdr_ty)
414 -- Must be done lazily for just the same reason as the
415 -- type of a data con; to avoid sucking in types that
416 -- it mentions unless it's necessary to do so
417 ; return (op_name, dm, op_ty) }
418
419 tc_at cls (IfaceAT tc_decl if_def)
420 = do ATyCon tc <- tc_iface_decl (AssocFamilyTyCon cls) ignore_prags tc_decl
421 mb_def <- case if_def of
422 Nothing -> return Nothing
423 Just def -> forkM (mk_at_doc tc) $
424 extendIfaceTyVarEnv (tyConTyVars tc) $
425 do { tc_def <- tcIfaceType def
426 ; return (Just tc_def) }
427 -- Must be done lazily in case the RHS of the defaults mention
428 -- the type constructor being defined here
429 -- e.g. type AT a; type AT b = AT [b] Trac #8002
430 return (ATI tc mb_def)
431
432 mk_sc_doc pred = ptext (sLit "Superclass") <+> ppr pred
433 mk_at_doc tc = ptext (sLit "Associated type") <+> ppr tc
434 mk_op_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
435
436 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
437 ; tvs2' <- mapM tcIfaceTyVar tvs2
438 ; return (tvs1', tvs2') }
439
440 tc_iface_decl _ _ (IfaceAxiom { ifName = ax_occ, ifTyCon = tc
441 , ifAxBranches = branches, ifRole = role })
442 = do { tc_name <- lookupIfaceTop ax_occ
443 ; tc_tycon <- tcIfaceTyCon tc
444 ; tc_branches <- tc_ax_branches branches
445 ; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
446 , co_ax_name = tc_name
447 , co_ax_tc = tc_tycon
448 , co_ax_role = role
449 , co_ax_branches = toBranchList tc_branches
450 , co_ax_implicit = False }
451 ; return (ACoAxiom axiom) }
452
453 tc_iface_decl _ _ (IfacePatSyn{ ifName = occ_name
454 , ifPatMatcher = if_matcher
455 , ifPatBuilder = if_builder
456 , ifPatIsInfix = is_infix
457 , ifPatUnivTvs = univ_tvs
458 , ifPatExTvs = ex_tvs
459 , ifPatProvCtxt = prov_ctxt
460 , ifPatReqCtxt = req_ctxt
461 , ifPatArgs = args
462 , ifPatTy = pat_ty })
463 = do { name <- lookupIfaceTop occ_name
464 ; traceIf (ptext (sLit "tc_iface_decl") <+> ppr name)
465 ; matcher <- tc_pr if_matcher
466 ; builder <- fmapMaybeM tc_pr if_builder
467 ; bindIfaceTyVars univ_tvs $ \univ_tvs -> do
468 { bindIfaceTyVars ex_tvs $ \ex_tvs -> do
469 { patsyn <- forkM (mk_doc name) $
470 do { prov_theta <- tcIfaceCtxt prov_ctxt
471 ; req_theta <- tcIfaceCtxt req_ctxt
472 ; pat_ty <- tcIfaceType pat_ty
473 ; arg_tys <- mapM tcIfaceType args
474 ; return $ buildPatSyn name is_infix matcher builder
475 (univ_tvs, req_theta) (ex_tvs, prov_theta)
476 arg_tys pat_ty }
477 ; return $ AConLike . PatSynCon $ patsyn }}}
478 where
479 mk_doc n = ptext (sLit "Pattern synonym") <+> ppr n
480 tc_pr :: (IfExtName, Bool) -> IfL (Id, Bool)
481 tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
482 ; return (id, b) }
483
484 tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
485 tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
486
487 tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
488 tc_ax_branch prev_branches
489 (IfaceAxBranch { ifaxbTyVars = tv_bndrs, ifaxbLHS = lhs, ifaxbRHS = rhs
490 , ifaxbRoles = roles, ifaxbIncomps = incomps })
491 = bindIfaceTyVars_AT tv_bndrs $ \ tvs -> do
492 -- The _AT variant is needed here; see Note [CoAxBranch type variables] in CoAxiom
493 { tc_lhs <- tcIfaceTcArgs lhs -- See Note [Checking IfaceTypes vs IfaceKinds]
494 ; tc_rhs <- tcIfaceType rhs
495 ; let br = CoAxBranch { cab_loc = noSrcSpan
496 , cab_tvs = tvs
497 , cab_lhs = tc_lhs
498 , cab_roles = roles
499 , cab_rhs = tc_rhs
500 , cab_incomps = map (prev_branches !!) incomps }
501 ; return (prev_branches ++ [br]) }
502
503 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
504 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
505 = case if_cons of
506 IfAbstractTyCon dis -> return (AbstractTyCon dis)
507 IfDataFamTyCon -> return DataFamilyTyCon
508 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
509 ; return (mkDataTyConRhs data_cons) }
510 IfNewTyCon con -> do { data_con <- tc_con_decl con
511 ; mkNewTyConRhs tycon_name tycon data_con }
512 where
513 tc_con_decl (IfCon { ifConInfix = is_infix,
514 ifConExTvs = ex_tvs,
515 ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
516 ifConArgTys = args, ifConFields = field_lbls,
517 ifConStricts = if_stricts})
518 = -- Universally-quantified tyvars are shared with
519 -- parent TyCon, and are alrady in scope
520 bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
521 { traceIf (text "Start interface-file tc_con_decl" <+> ppr occ)
522 ; name <- lookupIfaceTop occ
523
524 -- Read the context and argument types, but lazily for two reasons
525 -- (a) to avoid looking tugging on a recursive use of
526 -- the type itself, which is knot-tied
527 -- (b) to avoid faulting in the component types unless
528 -- they are really needed
529 ; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc name) $
530 do { eq_spec <- tcIfaceEqSpec spec
531 ; theta <- tcIfaceCtxt ctxt
532 ; arg_tys <- mapM tcIfaceType args
533 ; stricts <- mapM tc_strict if_stricts
534 -- The IfBang field can mention
535 -- the type itself; hence inside forkM
536 ; return (eq_spec, theta, arg_tys, stricts) }
537 ; lbl_names <- mapM lookupIfaceTop field_lbls
538
539 -- Remember, tycon is the representation tycon
540 ; let orig_res_ty = mkFamilyTyConApp tycon
541 (substTyVars (mkTopTvSubst eq_spec) tc_tyvars)
542
543 ; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr name))
544 name is_infix
545 stricts -- Pass the HsImplBangs (i.e. final decisions
546 -- to buildDataCon; it'll use these to guide
547 -- the construction of a worker
548 lbl_names
549 tc_tyvars ex_tyvars
550 eq_spec theta
551 arg_tys orig_res_ty tycon
552 ; traceIf (text "Done interface-file tc_con_decl" <+> ppr name)
553 ; return con }
554 mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
555
556 tc_strict :: IfaceBang -> IfL HsImplBang
557 tc_strict IfNoBang = return HsNoBang
558 tc_strict IfStrict = return HsStrict
559 tc_strict IfUnpack = return (HsUnpack Nothing)
560 tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
561 ; return (HsUnpack (Just co)) }
562
563 tcIfaceEqSpec :: IfaceEqSpec -> IfL [(TyVar, Type)]
564 tcIfaceEqSpec spec
565 = mapM do_item spec
566 where
567 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
568 ; ty <- tcIfaceType if_ty
569 ; return (tv,ty) }
570
571 {-
572 Note [Synonym kind loop]
573 ~~~~~~~~~~~~~~~~~~~~~~~~
574 Notice that we eagerly grab the *kind* from the interface file, but
575 build a forkM thunk for the *rhs* (and family stuff). To see why,
576 consider this (Trac #2412)
577
578 M.hs: module M where { import X; data T = MkT S }
579 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
580 M.hs-boot: module M where { data T }
581
582 When kind-checking M.hs we need S's kind. But we do not want to
583 find S's kind from (typeKind S-rhs), because we don't want to look at
584 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
585 be defined, and we must not do that until we've finished with M.T.
586
587 Solution: record S's kind in the interface file; now we can safely
588 look at it.
589
590 ************************************************************************
591 * *
592 Instances
593 * *
594 ************************************************************************
595 -}
596
597 tcIfaceInst :: IfaceClsInst -> IfL ClsInst
598 tcIfaceInst (IfaceClsInst { ifDFun = dfun_occ, ifOFlag = oflag
599 , ifInstCls = cls, ifInstTys = mb_tcs
600 , ifInstOrph = orph })
601 = do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
602 tcIfaceExtId dfun_occ
603 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
604 ; return (mkImportedInstance cls mb_tcs' dfun oflag orph) }
605
606 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
607 tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
608 , ifFamInstAxiom = axiom_name } )
609 = do { axiom' <- forkM (ptext (sLit "Axiom") <+> ppr axiom_name) $
610 tcIfaceCoAxiom axiom_name
611 -- will panic if branched, but that's OK
612 ; let axiom'' = toUnbranchedAxiom axiom'
613 mb_tcs' = map (fmap ifaceTyConName) mb_tcs
614 ; return (mkImportedFamInst fam mb_tcs' axiom'') }
615
616 {-
617 ************************************************************************
618 * *
619 Rules
620 * *
621 ************************************************************************
622
623 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
624 are in the type environment. However, remember that typechecking a Rule may
625 (as a side effect) augment the type envt, and so we may need to iterate the process.
626 -}
627
628 tcIfaceRules :: Bool -- True <=> ignore rules
629 -> [IfaceRule]
630 -> IfL [CoreRule]
631 tcIfaceRules ignore_prags if_rules
632 | ignore_prags = return []
633 | otherwise = mapM tcIfaceRule if_rules
634
635 tcIfaceRule :: IfaceRule -> IfL CoreRule
636 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
637 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
638 ifRuleAuto = auto, ifRuleOrph = orph })
639 = do { ~(bndrs', args', rhs') <-
640 -- Typecheck the payload lazily, in the hope it'll never be looked at
641 forkM (ptext (sLit "Rule") <+> ftext name) $
642 bindIfaceBndrs bndrs $ \ bndrs' ->
643 do { args' <- mapM tcIfaceExpr args
644 ; rhs' <- tcIfaceExpr rhs
645 ; return (bndrs', args', rhs') }
646 ; let mb_tcs = map ifTopFreeName args
647 ; this_mod <- getIfModule
648 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
649 ru_bndrs = bndrs', ru_args = args',
650 ru_rhs = occurAnalyseExpr rhs',
651 ru_rough = mb_tcs,
652 ru_origin = this_mod,
653 ru_orphan = orph,
654 ru_auto = auto,
655 ru_local = False }) } -- An imported RULE is never for a local Id
656 -- or, even if it is (module loop, perhaps)
657 -- we'll just leave it in the non-local set
658 where
659 -- This function *must* mirror exactly what Rules.roughTopNames does
660 -- We could have stored the ru_rough field in the iface file
661 -- but that would be redundant, I think.
662 -- The only wrinkle is that we must not be deceived by
663 -- type synonyms at the top of a type arg. Since
664 -- we can't tell at this point, we are careful not
665 -- to write them out in coreRuleToIfaceRule
666 ifTopFreeName :: IfaceExpr -> Maybe Name
667 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
668 ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (tcArgsIfaceTypes ts)))
669 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
670 ifTopFreeName (IfaceExt n) = Just n
671 ifTopFreeName _ = Nothing
672
673 {-
674 ************************************************************************
675 * *
676 Annotations
677 * *
678 ************************************************************************
679 -}
680
681 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
682 tcIfaceAnnotations = mapM tcIfaceAnnotation
683
684 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
685 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
686 target' <- tcIfaceAnnTarget target
687 return $ Annotation {
688 ann_target = target',
689 ann_value = serialized
690 }
691
692 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
693 tcIfaceAnnTarget (NamedTarget occ) = do
694 name <- lookupIfaceTop occ
695 return $ NamedTarget name
696 tcIfaceAnnTarget (ModuleTarget mod) = do
697 return $ ModuleTarget mod
698
699 {-
700 ************************************************************************
701 * *
702 Vectorisation information
703 * *
704 ************************************************************************
705 -}
706
707 -- We need access to the type environment as we need to look up information about type constructors
708 -- (i.e., their data constructors and whether they are class type constructors). If a vectorised
709 -- type constructor or class is defined in the same module as where it is vectorised, we cannot
710 -- look that information up from the type constructor that we obtained via a 'forkM'ed
711 -- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
712 -- and again and again...
713 --
714 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
715 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
716 { ifaceVectInfoVar = vars
717 , ifaceVectInfoTyCon = tycons
718 , ifaceVectInfoTyConReuse = tyconsReuse
719 , ifaceVectInfoParallelVars = parallelVars
720 , ifaceVectInfoParallelTyCons = parallelTyCons
721 })
722 = do { let parallelTyConsSet = mkNameSet parallelTyCons
723 ; vVars <- mapM vectVarMapping vars
724 ; let varsSet = mkVarSet (map fst vVars)
725 ; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
726 ; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
727 ; vParallelVars <- mapM vectVar parallelVars
728 ; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
729 ; return $ VectInfo
730 { vectInfoVar = mkVarEnv vVars `extendVarEnvList` concat vScSels
731 , vectInfoTyCon = mkNameEnv vTyCons
732 , vectInfoDataCon = mkNameEnv (concat vDataCons)
733 , vectInfoParallelVars = mkVarSet vParallelVars
734 , vectInfoParallelTyCons = parallelTyConsSet
735 }
736 }
737 where
738 vectVarMapping name
739 = do { vName <- lookupOrig mod (mkLocalisedOccName mod mkVectOcc name)
740 ; var <- forkM (ptext (sLit "vect var") <+> ppr name) $
741 tcIfaceExtId name
742 ; vVar <- forkM (ptext (sLit "vect vVar [mod =") <+>
743 ppr mod <> ptext (sLit "; nameModule =") <+>
744 ppr (nameModule name) <> ptext (sLit "]") <+> ppr vName) $
745 tcIfaceExtId vName
746 ; return (var, (var, vVar))
747 }
748 -- where
749 -- lookupLocalOrExternalId name
750 -- = do { let mb_id = lookupTypeEnv typeEnv name
751 -- ; case mb_id of
752 -- -- id is local
753 -- Just (AnId id) -> return id
754 -- -- name is not an Id => internal inconsistency
755 -- Just _ -> notAnIdErr
756 -- -- Id is external
757 -- Nothing -> tcIfaceExtId name
758 -- }
759 --
760 -- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
761
762 vectVar name
763 = forkM (ptext (sLit "vect scalar var") <+> ppr name) $
764 tcIfaceExtId name
765
766 vectTyConVectMapping vars name
767 = do { vName <- lookupOrig mod (mkLocalisedOccName mod mkVectTyConOcc name)
768 ; vectTyConMapping vars name vName
769 }
770
771 vectTyConReuseMapping vars name
772 = vectTyConMapping vars name name
773
774 vectTyConMapping vars name vName
775 = do { tycon <- lookupLocalOrExternalTyCon name
776 ; vTycon <- forkM (ptext (sLit "vTycon of") <+> ppr vName) $
777 lookupLocalOrExternalTyCon vName
778
779 -- Map the data constructors of the original type constructor to those of the
780 -- vectorised type constructor /unless/ the type constructor was vectorised
781 -- abstractly; if it was vectorised abstractly, the workers of its data constructors
782 -- do not appear in the set of vectorised variables.
783 --
784 -- NB: This is lazy! We don't pull at the type constructors before we actually use
785 -- the data constructor mapping.
786 ; let isAbstract | isClassTyCon tycon = False
787 | datacon:_ <- tyConDataCons tycon
788 = not $ dataConWrapId datacon `elemVarSet` vars
789 | otherwise = True
790 vDataCons | isAbstract = []
791 | otherwise = [ (dataConName datacon, (datacon, vDatacon))
792 | (datacon, vDatacon) <- zip (tyConDataCons tycon)
793 (tyConDataCons vTycon)
794 ]
795
796 -- Map the (implicit) superclass and methods selectors as they don't occur in
797 -- the var map.
798 vScSels | Just cls <- tyConClass_maybe tycon
799 , Just vCls <- tyConClass_maybe vTycon
800 = [ (sel, (sel, vSel))
801 | (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
802 ]
803 | otherwise
804 = []
805
806 ; return ( (name, (tycon, vTycon)) -- (T, T_v)
807 , vDataCons -- list of (Ci, Ci_v)
808 , vScSels -- list of (seli, seli_v)
809 )
810 }
811 where
812 -- we need a fully defined version of the type constructor to be able to extract
813 -- its data constructors etc.
814 lookupLocalOrExternalTyCon name
815 = do { let mb_tycon = lookupTypeEnv typeEnv name
816 ; case mb_tycon of
817 -- tycon is local
818 Just (ATyCon tycon) -> return tycon
819 -- name is not a tycon => internal inconsistency
820 Just _ -> notATyConErr
821 -- tycon is external
822 Nothing -> tcIfaceTyConByName name
823 }
824
825 notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
826
827 {-
828 ************************************************************************
829 * *
830 Types
831 * *
832 ************************************************************************
833 -}
834
835 tcIfaceType :: IfaceType -> IfL Type
836 tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
837 tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
838 tcIfaceType (IfaceLitTy l) = do { l1 <- tcIfaceTyLit l; return (LitTy l1) }
839 tcIfaceType (IfaceFunTy t1 t2) = tcIfaceTypeFun t1 t2
840 tcIfaceType (IfaceDFunTy t1 t2) = tcIfaceTypeFun t1 t2
841 tcIfaceType (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
842 tcIfaceType (IfaceTyConApp tc tks) = do { tc' <- tcIfaceTyCon tc
843 ; tks' <- tcIfaceTcArgs tks
844 ; return (mkTyConApp tc' tks') }
845 tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
846
847 tcIfaceTypeFun :: IfaceType -> IfaceType -> IfL Type
848 tcIfaceTypeFun t1 t2 = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
849
850 tcIfaceKind :: IfaceKind -> IfL Type
851 tcIfaceKind (IfaceAppTy t1 t2) = do { t1' <- tcIfaceKind t1; t2' <- tcIfaceKind t2; return (AppTy t1' t2') }
852 tcIfaceKind (IfaceFunTy t1 t2) = tcIfaceKindFun t1 t2
853 tcIfaceKind (IfaceDFunTy t1 t2) = tcIfaceKindFun t1 t2
854 tcIfaceKind (IfaceLitTy l) = pprPanic "tcIfaceKind" (ppr l)
855 tcIfaceKind k = tcIfaceType k
856
857 tcIfaceKindFun :: IfaceKind -> IfaceKind -> IfL Type
858 tcIfaceKindFun t1 t2 = do { t1' <- tcIfaceKind t1; t2' <- tcIfaceKind t2; return (FunTy t1' t2') }
859
860 tcIfaceTupleTy :: TupleSort -> IfaceTyConInfo -> IfaceTcArgs -> IfL Type
861 tcIfaceTupleTy sort info args
862 = do { args' <- tcIfaceTcArgs args
863 ; let arity = length args'
864 ; base_tc <- tcTupleTyCon sort arity
865 ; case info of
866 NoIfaceTyConInfo
867 -> return (mkTyConApp base_tc args')
868
869 IfacePromotedTyCon
870 | Just tc <- promotableTyCon_maybe base_tc
871 -> return (mkTyConApp tc args')
872 | otherwise
873 -> panic "tcIfaceTupleTy" (ppr base_tc)
874
875 IfacePromotedDataCon
876 -> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
877 kind_args = map typeKind args'
878 ; return (mkTyConApp tc (kind_args ++ args')) } }
879
880 tcTupleTyCon :: TupleSort -> Arity -> IfL TyCon
881 tcTupleTyCon sort arity
882 = case sort of
883 ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
884 ; return (tyThingTyCon thing) }
885 BoxedTuple -> return (tupleTyCon Boxed arity)
886 UnboxedTuple -> return (tupleTyCon Unboxed arity)
887
888 tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
889 tcIfaceTcArgs args
890 = case args of
891 ITC_Type t ts ->
892 do { t' <- tcIfaceType t
893 ; ts' <- tcIfaceTcArgs ts
894 ; return (t':ts') }
895 ITC_Kind k ks ->
896 do { k' <- tcIfaceKind k
897 ; ks' <- tcIfaceTcArgs ks
898 ; return (k':ks') }
899 ITC_Nil -> return []
900 -----------------------------------------
901 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
902 tcIfaceCtxt sts = mapM tcIfaceType sts
903
904 -----------------------------------------
905 tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
906 tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
907 tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
908
909 {-
910 ************************************************************************
911 * *
912 Coercions
913 * *
914 ************************************************************************
915 -}
916
917 tcIfaceCo :: IfaceCoercion -> IfL Coercion
918 tcIfaceCo (IfaceReflCo r t) = mkReflCo r <$> tcIfaceType t
919 tcIfaceCo (IfaceFunCo r c1 c2) = mkFunCo r <$> tcIfaceCo c1 <*> tcIfaceCo c2
920 tcIfaceCo (IfaceTyConAppCo r tc cs) = mkTyConAppCo r <$> tcIfaceTyCon tc
921 <*> mapM tcIfaceCo cs
922 tcIfaceCo (IfaceAppCo c1 c2) = mkAppCo <$> tcIfaceCo c1
923 <*> tcIfaceCo c2
924 tcIfaceCo (IfaceForAllCo tv c) = bindIfaceTyVar tv $ \ tv' ->
925 mkForAllCo tv' <$> tcIfaceCo c
926 tcIfaceCo (IfaceCoVarCo n) = mkCoVarCo <$> tcIfaceCoVar n
927 tcIfaceCo (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n
928 <*> pure i
929 <*> mapM tcIfaceCo cs
930 tcIfaceCo (IfaceUnivCo s r t1 t2) = UnivCo s r <$> tcIfaceType t1
931 <*> tcIfaceType t2
932 tcIfaceCo (IfaceSymCo c) = SymCo <$> tcIfaceCo c
933 tcIfaceCo (IfaceTransCo c1 c2) = TransCo <$> tcIfaceCo c1
934 <*> tcIfaceCo c2
935 tcIfaceCo (IfaceInstCo c1 t2) = InstCo <$> tcIfaceCo c1
936 <*> tcIfaceType t2
937 tcIfaceCo (IfaceNthCo d c) = NthCo d <$> tcIfaceCo c
938 tcIfaceCo (IfaceLRCo lr c) = LRCo lr <$> tcIfaceCo c
939 tcIfaceCo (IfaceSubCo c) = SubCo <$> tcIfaceCo c
940 tcIfaceCo (IfaceAxiomRuleCo ax tys cos) = AxiomRuleCo
941 <$> tcIfaceCoAxiomRule ax
942 <*> mapM tcIfaceType tys
943 <*> mapM tcIfaceCo cos
944
945 tcIfaceCoVar :: FastString -> IfL CoVar
946 tcIfaceCoVar = tcIfaceLclId
947
948 tcIfaceCoAxiomRule :: FastString -> IfL CoAxiomRule
949 tcIfaceCoAxiomRule n =
950 case Map.lookup n typeNatCoAxiomRules of
951 Just ax -> return ax
952 _ -> pprPanic "tcIfaceCoAxiomRule" (ppr n)
953
954 {-
955 ************************************************************************
956 * *
957 Core
958 * *
959 ************************************************************************
960 -}
961
962 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
963 tcIfaceExpr (IfaceType ty)
964 = Type <$> tcIfaceType ty
965
966 tcIfaceExpr (IfaceCo co)
967 = Coercion <$> tcIfaceCo co
968
969 tcIfaceExpr (IfaceCast expr co)
970 = Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
971
972 tcIfaceExpr (IfaceLcl name)
973 = Var <$> tcIfaceLclId name
974
975 tcIfaceExpr (IfaceExt gbl)
976 = Var <$> tcIfaceExtId gbl
977
978 tcIfaceExpr (IfaceLit lit)
979 = do lit' <- tcIfaceLit lit
980 return (Lit lit')
981
982 tcIfaceExpr (IfaceFCall cc ty) = do
983 ty' <- tcIfaceType ty
984 u <- newUnique
985 dflags <- getDynFlags
986 return (Var (mkFCallId dflags u cc ty'))
987
988 tcIfaceExpr (IfaceTuple sort args)
989 = do { args' <- mapM tcIfaceExpr args
990 ; tc <- tcTupleTyCon sort arity
991 ; let con_args = map (Type . exprType) args' ++ args'
992 -- Put the missing type arguments back in
993 con_id = dataConWorkId (tyConSingleDataCon tc)
994 ; return (mkApps (Var con_id) con_args) }
995 where
996 arity = length args
997
998 tcIfaceExpr (IfaceLam (bndr, os) body)
999 = bindIfaceBndr bndr $ \bndr' ->
1000 Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
1001 where
1002 tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
1003 tcIfaceOneShot _ b = b
1004
1005 tcIfaceExpr (IfaceApp fun arg)
1006 = tcIfaceApps fun arg
1007
1008 tcIfaceExpr (IfaceECase scrut ty)
1009 = do { scrut' <- tcIfaceExpr scrut
1010 ; ty' <- tcIfaceType ty
1011 ; return (castBottomExpr scrut' ty') }
1012
1013 tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
1014 scrut' <- tcIfaceExpr scrut
1015 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
1016 let
1017 scrut_ty = exprType scrut'
1018 case_bndr' = mkLocalId case_bndr_name scrut_ty
1019 tc_app = splitTyConApp scrut_ty
1020 -- NB: Won't always succeed (polymorphic case)
1021 -- but won't be demanded in those cases
1022 -- NB: not tcSplitTyConApp; we are looking at Core here
1023 -- look through non-rec newtypes to find the tycon that
1024 -- corresponds to the datacon in this case alternative
1025
1026 extendIfaceIdEnv [case_bndr'] $ do
1027 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
1028 return (Case scrut' case_bndr' (coreAltsType alts') alts')
1029
1030 tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info) rhs) body)
1031 = do { name <- newIfaceName (mkVarOccFS fs)
1032 ; ty' <- tcIfaceType ty
1033 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1034 name ty' info
1035 ; let id = mkLocalIdWithInfo name ty' id_info
1036 ; rhs' <- tcIfaceExpr rhs
1037 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
1038 ; return (Let (NonRec id rhs') body') }
1039
1040 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
1041 = do { ids <- mapM tc_rec_bndr (map fst pairs)
1042 ; extendIfaceIdEnv ids $ do
1043 { pairs' <- zipWithM tc_pair pairs ids
1044 ; body' <- tcIfaceExpr body
1045 ; return (Let (Rec pairs') body') } }
1046 where
1047 tc_rec_bndr (IfLetBndr fs ty _)
1048 = do { name <- newIfaceName (mkVarOccFS fs)
1049 ; ty' <- tcIfaceType ty
1050 ; return (mkLocalId name ty') }
1051 tc_pair (IfLetBndr _ _ info, rhs) id
1052 = do { rhs' <- tcIfaceExpr rhs
1053 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1054 (idName id) (idType id) info
1055 ; return (setIdInfo id id_info, rhs') }
1056
1057 tcIfaceExpr (IfaceTick tickish expr) = do
1058 expr' <- tcIfaceExpr expr
1059 -- If debug flag is not set: Ignore source notes
1060 dbgFlag <- fmap (gopt Opt_Debug) getDynFlags
1061 case tickish of
1062 IfaceSource{} | not dbgFlag
1063 -> return expr'
1064 _otherwise -> do
1065 tickish' <- tcIfaceTickish tickish
1066 return (Tick tickish' expr')
1067
1068 -------------------------
1069 tcIfaceApps :: IfaceExpr -> IfaceExpr -> IfL CoreExpr
1070 -- See Note [Checking IfaceTypes vs IfaceKinds]
1071 tcIfaceApps fun arg
1072 = go_down fun [arg]
1073 where
1074 go_down (IfaceApp fun arg) args = go_down fun (arg:args)
1075 go_down fun args = do { fun' <- tcIfaceExpr fun
1076 ; go_up fun' (exprType fun') args }
1077
1078 go_up :: CoreExpr -> Type -> [IfaceExpr] -> IfL CoreExpr
1079 go_up fun _ [] = return fun
1080 go_up fun fun_ty (IfaceType t : args)
1081 | Just (tv,body_ty) <- splitForAllTy_maybe fun_ty
1082 = do { t' <- if isKindVar tv
1083 then tcIfaceKind t
1084 else tcIfaceType t
1085 ; let fun_ty' = substTyWith [tv] [t'] body_ty
1086 ; go_up (App fun (Type t')) fun_ty' args }
1087 go_up fun fun_ty (arg : args)
1088 | Just (_, fun_ty') <- splitFunTy_maybe fun_ty
1089 = do { arg' <- tcIfaceExpr arg
1090 ; go_up (App fun arg') fun_ty' args }
1091 go_up fun fun_ty args = pprPanic "tcIfaceApps" (ppr fun $$ ppr fun_ty $$ ppr args)
1092
1093 -------------------------
1094 tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
1095 tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
1096 tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
1097 tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
1098
1099 -------------------------
1100 tcIfaceLit :: Literal -> IfL Literal
1101 -- Integer literals deserialise to (LitInteger i <error thunk>)
1102 -- so tcIfaceLit just fills in the type.
1103 -- See Note [Integer literals] in Literal
1104 tcIfaceLit (LitInteger i _)
1105 = do t <- tcIfaceTyConByName integerTyConName
1106 return (mkLitInteger i (mkTyConTy t))
1107 tcIfaceLit lit = return lit
1108
1109 -------------------------
1110 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
1111 -> (IfaceConAlt, [FastString], IfaceExpr)
1112 -> IfL (AltCon, [TyVar], CoreExpr)
1113 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
1114 = ASSERT( null names ) do
1115 rhs' <- tcIfaceExpr rhs
1116 return (DEFAULT, [], rhs')
1117
1118 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
1119 = ASSERT( null names ) do
1120 lit' <- tcIfaceLit lit
1121 rhs' <- tcIfaceExpr rhs
1122 return (LitAlt lit', [], rhs')
1123
1124 -- A case alternative is made quite a bit more complicated
1125 -- by the fact that we omit type annotations because we can
1126 -- work them out. True enough, but its not that easy!
1127 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
1128 = do { con <- tcIfaceDataCon data_occ
1129 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
1130 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
1131 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
1132
1133 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
1134 -> IfL (AltCon, [TyVar], CoreExpr)
1135 tcIfaceDataAlt con inst_tys arg_strs rhs
1136 = do { us <- newUniqueSupply
1137 ; let uniqs = uniqsFromSupply us
1138 ; let (ex_tvs, arg_ids)
1139 = dataConRepFSInstPat arg_strs uniqs con inst_tys
1140
1141 ; rhs' <- extendIfaceTyVarEnv ex_tvs $
1142 extendIfaceIdEnv arg_ids $
1143 tcIfaceExpr rhs
1144 ; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
1145
1146 {-
1147 ************************************************************************
1148 * *
1149 IdInfo
1150 * *
1151 ************************************************************************
1152 -}
1153
1154 tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
1155 tcIdDetails _ IfVanillaId = return VanillaId
1156 tcIdDetails ty IfDFunId
1157 = return (DFunId (isNewTyCon (classTyCon cls)))
1158 where
1159 (_, _, cls, _) = tcSplitDFunTy ty
1160
1161 tcIdDetails _ (IfRecSelId tc naughty)
1162 = do { tc' <- tcIfaceTyCon tc
1163 ; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
1164
1165 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
1166 tcIdInfo ignore_prags name ty info
1167 | ignore_prags = return vanillaIdInfo
1168 | otherwise = case info of
1169 NoInfo -> return vanillaIdInfo
1170 HasInfo info -> foldlM tcPrag init_info info
1171 where
1172 -- Set the CgInfo to something sensible but uninformative before
1173 -- we start; default assumption is that it has CAFs
1174 init_info = vanillaIdInfo
1175
1176 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
1177 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
1178 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
1179 tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
1180 tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
1181
1182 -- The next two are lazy, so they don't transitively suck stuff in
1183 tcPrag info (HsUnfold lb if_unf)
1184 = do { unf <- tcUnfolding name ty info if_unf
1185 ; let info1 | lb = info `setOccInfo` strongLoopBreaker
1186 | otherwise = info
1187 ; return (info1 `setUnfoldingInfoLazily` unf) }
1188
1189 tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
1190 tcUnfolding name _ info (IfCoreUnfold stable if_expr)
1191 = do { dflags <- getDynFlags
1192 ; mb_expr <- tcPragExpr name if_expr
1193 ; let unf_src | stable = InlineStable
1194 | otherwise = InlineRhs
1195 ; return $ case mb_expr of
1196 Nothing -> NoUnfolding
1197 Just expr -> mkUnfolding dflags unf_src
1198 True {- Top level -}
1199 (isBottomingSig strict_sig)
1200 expr
1201 }
1202 where
1203 -- Strictness should occur before unfolding!
1204 strict_sig = strictnessInfo info
1205 tcUnfolding name _ _ (IfCompulsory if_expr)
1206 = do { mb_expr <- tcPragExpr name if_expr
1207 ; return (case mb_expr of
1208 Nothing -> NoUnfolding
1209 Just expr -> mkCompulsoryUnfolding expr) }
1210
1211 tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
1212 = do { mb_expr <- tcPragExpr name if_expr
1213 ; return (case mb_expr of
1214 Nothing -> NoUnfolding
1215 Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
1216 where
1217 guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
1218
1219 tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
1220 = bindIfaceBndrs bs $ \ bs' ->
1221 do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
1222 ; return (case mb_ops1 of
1223 Nothing -> noUnfolding
1224 Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
1225 where
1226 doc = text "Class ops for dfun" <+> ppr name
1227 (_, _, cls, _) = tcSplitDFunTy dfun_ty
1228
1229 {-
1230 For unfoldings we try to do the job lazily, so that we never type check
1231 an unfolding that isn't going to be looked at.
1232 -}
1233
1234 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
1235 tcPragExpr name expr
1236 = forkM_maybe doc $ do
1237 core_expr' <- tcIfaceExpr expr
1238
1239 -- Check for type consistency in the unfolding
1240 whenGOptM Opt_DoCoreLinting $ do
1241 in_scope <- get_in_scope
1242 dflags <- getDynFlags
1243 case lintUnfolding dflags noSrcLoc in_scope core_expr' of
1244 Nothing -> return ()
1245 Just fail_msg -> do { mod <- getIfModule
1246 ; pprPanic "Iface Lint failure"
1247 (vcat [ ptext (sLit "In interface for") <+> ppr mod
1248 , hang doc 2 fail_msg
1249 , ppr name <+> equals <+> ppr core_expr'
1250 , ptext (sLit "Iface expr =") <+> ppr expr ]) }
1251 return core_expr'
1252 where
1253 doc = text "Unfolding of" <+> ppr name
1254
1255 get_in_scope :: IfL [Var] -- Totally disgusting; but just for linting
1256 get_in_scope
1257 = do { (gbl_env, lcl_env) <- getEnvs
1258 ; rec_ids <- case if_rec_types gbl_env of
1259 Nothing -> return []
1260 Just (_, get_env) -> do
1261 { type_env <- setLclEnv () get_env
1262 ; return (typeEnvIds type_env) }
1263 ; return (varEnvElts (if_tv_env lcl_env) ++
1264 varEnvElts (if_id_env lcl_env) ++
1265 rec_ids) }
1266
1267 {-
1268 ************************************************************************
1269 * *
1270 Getting from Names to TyThings
1271 * *
1272 ************************************************************************
1273 -}
1274
1275 tcIfaceGlobal :: Name -> IfL TyThing
1276 tcIfaceGlobal name
1277 | Just thing <- wiredInNameTyThing_maybe name
1278 -- Wired-in things include TyCons, DataCons, and Ids
1279 -- Even though we are in an interface file, we want to make
1280 -- sure the instances and RULES of this thing (particularly TyCon) are loaded
1281 -- Imagine: f :: Double -> Double
1282 = do { ifCheckWiredInThing thing; return thing }
1283
1284 | otherwise
1285 = do { env <- getGblEnv
1286 ; case if_rec_types env of { -- Note [Tying the knot]
1287 Just (mod, get_type_env)
1288 | nameIsLocalOrFrom mod name
1289 -> do -- It's defined in the module being compiled
1290 { type_env <- setLclEnv () get_type_env -- yuk
1291 ; case lookupNameEnv type_env name of
1292 Just thing -> return thing
1293 Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
1294 (ppr name $$ ppr type_env) }
1295
1296 ; _ -> do
1297
1298 { hsc_env <- getTopEnv
1299 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1300 ; case mb_thing of {
1301 Just thing -> return thing ;
1302 Nothing -> do
1303
1304 { mb_thing <- importDecl name -- It's imported; go get it
1305 ; case mb_thing of
1306 Failed err -> failIfM err
1307 Succeeded thing -> return thing
1308 }}}}}
1309
1310 -- Note [Tying the knot]
1311 -- ~~~~~~~~~~~~~~~~~~~~~
1312 -- The if_rec_types field is used in two situations:
1313 --
1314 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1315 -- Then we look up M.T in M's type environment, which is splatted into if_rec_types
1316 -- after we've built M's type envt.
1317 --
1318 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1319 -- is up to date. So we call typecheckIface on M.hi. This splats M.T into
1320 -- if_rec_types so that the (lazily typechecked) decls see all the other decls
1321 --
1322 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1323 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1324 -- emasculated form (e.g. lacking data constructors).
1325
1326 tcIfaceTyConByName :: IfExtName -> IfL TyCon
1327 tcIfaceTyConByName name
1328 = do { thing <- tcIfaceGlobal name
1329 ; return (tyThingTyCon thing) }
1330
1331 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1332 tcIfaceTyCon (IfaceTyCon name info)
1333 = do { thing <- tcIfaceGlobal name
1334 ; case info of
1335 NoIfaceTyConInfo -> return (tyThingTyCon thing)
1336 IfacePromotedDataCon -> return (promoteDataCon (tyThingDataCon thing))
1337 -- Same Name as its underlying DataCon
1338 IfacePromotedTyCon -> return (promote_tc (tyThingTyCon thing)) }
1339 -- Same Name as its underlying TyCon
1340 where
1341 promote_tc tc
1342 | Just prom_tc <- promotableTyCon_maybe tc = prom_tc
1343 | isSuperKind (tyConKind tc) = tc
1344 | otherwise = pprPanic "tcIfaceTyCon" (ppr name $$ ppr tc)
1345
1346 tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
1347 tcIfaceCoAxiom name = do { thing <- tcIfaceGlobal name
1348 ; return (tyThingCoAxiom thing) }
1349
1350 tcIfaceDataCon :: Name -> IfL DataCon
1351 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1352 ; case thing of
1353 AConLike (RealDataCon dc) -> return dc
1354 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1355
1356 tcIfaceExtId :: Name -> IfL Id
1357 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1358 ; case thing of
1359 AnId id -> return id
1360 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1361
1362 {-
1363 ************************************************************************
1364 * *
1365 Bindings
1366 * *
1367 ************************************************************************
1368 -}
1369
1370 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1371 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1372 = do { name <- newIfaceName (mkVarOccFS fs)
1373 ; ty' <- tcIfaceType ty
1374 ; let id = mkLocalId name ty'
1375 ; extendIfaceIdEnv [id] (thing_inside id) }
1376 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1377 = bindIfaceTyVar bndr thing_inside
1378
1379 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1380 bindIfaceBndrs [] thing_inside = thing_inside []
1381 bindIfaceBndrs (b:bs) thing_inside
1382 = bindIfaceBndr b $ \ b' ->
1383 bindIfaceBndrs bs $ \ bs' ->
1384 thing_inside (b':bs')
1385
1386 -----------------------
1387 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1388 bindIfaceTyVar (occ,kind) thing_inside
1389 = do { name <- newIfaceName (mkTyVarOccFS occ)
1390 ; tyvar <- mk_iface_tyvar name kind
1391 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1392
1393 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1394 bindIfaceTyVars bndrs thing_inside
1395 = do { names <- newIfaceNames (map mkTyVarOccFS occs)
1396 ; let (kis_kind, tys_kind) = span isSuperIfaceKind kinds
1397 (kis_name, tys_name) = splitAt (length kis_kind) names
1398 -- We need to bring the kind variables in scope since type
1399 -- variables may mention them.
1400 ; kvs <- zipWithM mk_iface_tyvar kis_name kis_kind
1401 ; extendIfaceTyVarEnv kvs $ do
1402 { tvs <- zipWithM mk_iface_tyvar tys_name tys_kind
1403 ; extendIfaceTyVarEnv tvs (thing_inside (kvs ++ tvs)) } }
1404 where
1405 (occs,kinds) = unzip bndrs
1406
1407 isSuperIfaceKind :: IfaceKind -> Bool
1408 isSuperIfaceKind (IfaceTyConApp tc ITC_Nil) = ifaceTyConName tc == superKindTyConName
1409 isSuperIfaceKind _ = False
1410
1411 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1412 mk_iface_tyvar name ifKind
1413 = do { kind <- tcIfaceKind ifKind
1414 ; return (Var.mkTyVar name kind) }
1415
1416 bindIfaceTyVars_AT :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1417 -- Used for type variable in nested associated data/type declarations
1418 -- where some of the type variables are already in scope
1419 -- class C a where { data T a b }
1420 -- Here 'a' is in scope when we look at the 'data T'
1421 bindIfaceTyVars_AT [] thing_inside
1422 = thing_inside []
1423 bindIfaceTyVars_AT (b@(tv_occ,_) : bs) thing_inside
1424 = do { mb_tv <- lookupIfaceTyVar tv_occ
1425 ; let bind_b :: (TyVar -> IfL a) -> IfL a
1426 bind_b = case mb_tv of
1427 Just b' -> \k -> k b'
1428 Nothing -> bindIfaceTyVar b
1429 ; bind_b $ \b' ->
1430 bindIfaceTyVars_AT bs $ \bs' ->
1431 thing_inside (b':bs') }