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