2a563929109b2fd60c3672df7aea23d3e7919579
[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 {-# LANGUAGE NondecreasingIndentation #-}
11
12 module TcIface (
13 tcLookupImported_maybe,
14 importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
15 typecheckIfacesForMerging,
16 typecheckIfaceForInstantiate,
17 tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
18 tcIfaceVectInfo, tcIfaceAnnotations,
19 tcIfaceExpr, -- Desired by HERMIT (Trac #7683)
20 tcIfaceGlobal
21 ) where
22
23 #include "HsVersions.h"
24
25 import TcTypeNats(typeNatCoAxiomRules)
26 import IfaceSyn
27 import LoadIface
28 import IfaceEnv
29 import BuildTyCl
30 import TcRnMonad
31 import TcType
32 import Type
33 import Coercion
34 import CoAxiom
35 import TyCoRep -- needs to build types & coercions in a knot
36 import HscTypes
37 import Annotations
38 import InstEnv
39 import FamInstEnv
40 import CoreSyn
41 import CoreUtils
42 import CoreUnfold
43 import CoreLint
44 import MkCore
45 import Id
46 import MkId
47 import IdInfo
48 import Class
49 import TyCon
50 import ConLike
51 import DataCon
52 import PrelNames
53 import TysWiredIn
54 import Literal
55 import Var
56 import VarEnv
57 import VarSet
58 import Name
59 import NameEnv
60 import NameSet
61 import OccurAnal ( occurAnalyseExpr )
62 import Demand
63 import Module
64 import UniqFM
65 import UniqSupply
66 import Outputable
67 import Maybes
68 import SrcLoc
69 import DynFlags
70 import Util
71 import FastString
72 import BasicTypes hiding ( SuccessFlag(..) )
73 import ListSetOps
74 import GHC.Fingerprint
75 import qualified BooleanFormula as BF
76
77 import Data.List
78 import Control.Monad
79 import qualified Data.Map as Map
80
81 {-
82 This module takes
83
84 IfaceDecl -> TyThing
85 IfaceType -> Type
86 etc
87
88 An IfaceDecl is populated with RdrNames, and these are not renamed to
89 Names before typechecking, because there should be no scope errors etc.
90
91 -- For (b) consider: f = \$(...h....)
92 -- where h is imported, and calls f via an hi-boot file.
93 -- This is bad! But it is not seen as a staging error, because h
94 -- is indeed imported. We don't want the type-checker to black-hole
95 -- when simplifying and compiling the splice!
96 --
97 -- Simple solution: discard any unfolding that mentions a variable
98 -- bound in this module (and hence not yet processed).
99 -- The discarding happens when forkM finds a type error.
100
101
102 ************************************************************************
103 * *
104 Type-checking a complete interface
105 * *
106 ************************************************************************
107
108 Suppose we discover we don't need to recompile. Then we must type
109 check the old interface file. This is a bit different to the
110 incremental type checking we do as we suck in interface files. Instead
111 we do things similarly as when we are typechecking source decls: we
112 bring into scope the type envt for the interface all at once, using a
113 knot. Remember, the decls aren't necessarily in dependency order --
114 and even if they were, the type decls might be mutually recursive.
115
116 Note [Knot-tying typecheckIface]
117 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
118 Suppose we are typechecking an interface A.hi, and we come across
119 a Name for another entity defined in A.hi. How do we get the
120 'TyCon', in this case? There are three cases:
121
122 1) tcHiBootIface in TcIface: We're typechecking an hi-boot file in
123 preparation of checking if the hs file we're building
124 is compatible. In this case, we want all of the internal
125 TyCons to MATCH the ones that we just constructed during
126 typechecking: the knot is thus tied through if_rec_types.
127
128 2) retypecheckLoop in GhcMake: We are retypechecking a
129 mutually recursive cluster of hi files, in order to ensure
130 that all of the references refer to each other correctly.
131 In this case, the knot is tied through the HPT passed in,
132 which contains all of the interfaces we are in the process
133 of typechecking.
134
135 3) genModDetails in HscMain: We are typechecking an
136 old interface to generate the ModDetails. In this case,
137 we do the same thing as (2) and pass in an HPT with
138 the HomeModInfo being generated to tie knots.
139
140 The upshot is that the CLIENT of this function is responsible
141 for making sure that the knot is tied correctly. If you don't,
142 then you'll get a message saying that we couldn't load the
143 declaration you wanted.
144
145 BTW, in one-shot mode we never call typecheckIface; instead,
146 loadInterface handles type-checking interface. In that case,
147 knots are tied through the EPS. No problem!
148 -}
149
150 -- Clients of this function be careful, see Note [Knot-tying typecheckIface]
151 typecheckIface :: ModIface -- Get the decls from here
152 -> IfG ModDetails
153 typecheckIface iface
154 = initIfaceLcl (mi_semantic_module iface) (text "typecheckIface") (mi_boot iface) $ do
155 { -- Get the right set of decls and rules. If we are compiling without -O
156 -- we discard pragmas before typechecking, so that we don't "see"
157 -- information that we shouldn't. From a versioning point of view
158 -- It's not actually *wrong* to do so, but in fact GHCi is unable
159 -- to handle unboxed tuples, so it must not see unfoldings.
160 ignore_prags <- goptM Opt_IgnoreInterfacePragmas
161
162 -- Typecheck the decls. This is done lazily, so that the knot-tying
163 -- within this single module works out right. It's the callers
164 -- job to make sure the knot is tied.
165 ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
166 ; let type_env = mkNameEnv names_w_things
167
168 -- Now do those rules, instances and annotations
169 ; insts <- mapM tcIfaceInst (mi_insts iface)
170 ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
171 ; rules <- tcIfaceRules ignore_prags (mi_rules iface)
172 ; anns <- tcIfaceAnnotations (mi_anns iface)
173
174 -- Vectorisation information
175 ; vect_info <- tcIfaceVectInfo (mi_semantic_module iface) type_env (mi_vect_info iface)
176
177 -- Exports
178 ; exports <- ifaceExportNames (mi_exports iface)
179
180 -- Complete Sigs
181 ; complete_sigs <- tcIfaceCompleteSigs (mi_complete_sigs iface)
182
183 -- Finished
184 ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
185 -- Careful! If we tug on the TyThing thunks too early
186 -- we'll infinite loop with hs-boot. See #10083 for
187 -- an example where this would cause non-termination.
188 text "Type envt:" <+> ppr (map fst names_w_things)])
189 ; return $ ModDetails { md_types = type_env
190 , md_insts = insts
191 , md_fam_insts = fam_insts
192 , md_rules = rules
193 , md_anns = anns
194 , md_vect_info = vect_info
195 , md_exports = exports
196 , md_complete_sigs = complete_sigs
197 }
198 }
199
200 {-
201 ************************************************************************
202 * *
203 Typechecking for merging
204 * *
205 ************************************************************************
206 -}
207
208 -- | Returns true if an 'IfaceDecl' is for @data T@ (an abstract data type)
209 isAbstractIfaceDecl :: IfaceDecl -> Bool
210 isAbstractIfaceDecl IfaceData{ ifCons = IfAbstractTyCon } = True
211 isAbstractIfaceDecl IfaceClass{ ifBody = IfAbstractClass } = True
212 isAbstractIfaceDecl IfaceFamily{ ifFamFlav = IfaceAbstractClosedSynFamilyTyCon } = True
213 isAbstractIfaceDecl _ = False
214
215 ifMaybeRoles :: IfaceDecl -> Maybe [Role]
216 ifMaybeRoles IfaceData { ifRoles = rs } = Just rs
217 ifMaybeRoles IfaceSynonym { ifRoles = rs } = Just rs
218 ifMaybeRoles IfaceClass { ifRoles = rs } = Just rs
219 ifMaybeRoles _ = Nothing
220
221 -- | Merge two 'IfaceDecl's together, preferring a non-abstract one. If
222 -- both are non-abstract we pick one arbitrarily (and check for consistency
223 -- later.)
224 mergeIfaceDecl :: IfaceDecl -> IfaceDecl -> IfaceDecl
225 mergeIfaceDecl d1 d2
226 | isAbstractIfaceDecl d1 = d2 `withRolesFrom` d1
227 | isAbstractIfaceDecl d2 = d1 `withRolesFrom` d2
228 | IfaceClass{ ifBody = IfConcreteClass { ifSigs = ops1, ifMinDef = bf1 } } <- d1
229 , IfaceClass{ ifBody = IfConcreteClass { ifSigs = ops2, ifMinDef = bf2 } } <- d2
230 = let ops = nameEnvElts $
231 plusNameEnv_C mergeIfaceClassOp
232 (mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops1 ])
233 (mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops2 ])
234 in d1 { ifBody = (ifBody d1) {
235 ifSigs = ops,
236 ifMinDef = BF.mkOr [noLoc bf1, noLoc bf2]
237 }
238 } `withRolesFrom` d2
239 -- It doesn't matter; we'll check for consistency later when
240 -- we merge, see 'mergeSignatures'
241 | otherwise = d1 `withRolesFrom` d2
242
243 -- Note [Role merging]
244 -- ~~~~~~~~~~~~~~~~~~~
245 -- First, why might it be necessary to do a non-trivial role
246 -- merge? It may rescue a merge that might otherwise fail:
247 --
248 -- signature A where
249 -- type role T nominal representational
250 -- data T a b
251 --
252 -- signature A where
253 -- type role T representational nominal
254 -- data T a b
255 --
256 -- A module that defines T as representational in both arguments
257 -- would successfully fill both signatures, so it would be better
258 -- if if we merged the roles of these types in some nontrivial
259 -- way.
260 --
261 -- However, we have to be very careful about how we go about
262 -- doing this, because role subtyping is *conditional* on
263 -- the supertype being NOT representationally injective, e.g.,
264 -- if we have instead:
265 --
266 -- signature A where
267 -- type role T nominal representational
268 -- data T a b = T a b
269 --
270 -- signature A where
271 -- type role T representational nominal
272 -- data T a b = T a b
273 --
274 -- Should we merge the definitions of T so that the roles are R/R (or N/N)?
275 -- Absolutely not: neither resulting type is a subtype of the original
276 -- types (see Note [Role subtyping]), because data is not representationally
277 -- injective.
278 --
279 -- Thus, merging only occurs when BOTH TyCons in question are
280 -- representationally injective. If they're not, no merge.
281
282 withRolesFrom :: IfaceDecl -> IfaceDecl -> IfaceDecl
283 d1 `withRolesFrom` d2
284 | Just roles1 <- ifMaybeRoles d1
285 , Just roles2 <- ifMaybeRoles d2
286 , not (isRepInjectiveIfaceDecl d1 || isRepInjectiveIfaceDecl d2)
287 = d1 { ifRoles = mergeRoles roles1 roles2 }
288 | otherwise = d1
289 where
290 mergeRoles roles1 roles2 = zipWith max roles1 roles2
291
292 isRepInjectiveIfaceDecl :: IfaceDecl -> Bool
293 isRepInjectiveIfaceDecl IfaceData{ ifCons = IfDataTyCon _ } = True
294 isRepInjectiveIfaceDecl IfaceFamily{ ifFamFlav = IfaceDataFamilyTyCon } = True
295 isRepInjectiveIfaceDecl _ = False
296
297 mergeIfaceClassOp :: IfaceClassOp -> IfaceClassOp -> IfaceClassOp
298 mergeIfaceClassOp op1@(IfaceClassOp _ _ (Just _)) _ = op1
299 mergeIfaceClassOp _ op2 = op2
300
301 -- | Merge two 'OccEnv's of 'IfaceDecl's by 'OccName'.
302 mergeIfaceDecls :: OccEnv IfaceDecl -> OccEnv IfaceDecl -> OccEnv IfaceDecl
303 mergeIfaceDecls = plusOccEnv_C mergeIfaceDecl
304
305 -- | This is a very interesting function. Like typecheckIface, we want
306 -- to type check an interface file into a ModDetails. However, the use-case
307 -- for these ModDetails is different: we want to compare all of the
308 -- ModDetails to ensure they define compatible declarations, and then
309 -- merge them together. So in particular, we have to take a different
310 -- strategy for knot-tying: we first speculatively merge the declarations
311 -- to get the "base" truth for what we believe the types will be
312 -- (this is "type computation.") Then we read everything in relative
313 -- to this truth and check for compatibility.
314 --
315 -- During the merge process, we may need to nondeterministically
316 -- pick a particular declaration to use, if multiple signatures define
317 -- the declaration ('mergeIfaceDecl'). If, for all choices, there
318 -- are no type synonym cycles in the resulting merged graph, then
319 -- we can show that our choice cannot matter. Consider the
320 -- set of entities which the declarations depend on: by assumption
321 -- of acyclicity, we can assume that these have already been shown to be equal
322 -- to each other (otherwise merging will fail). Then it must
323 -- be the case that all candidate declarations here are type-equal
324 -- (the choice doesn't matter) or there is an inequality (in which
325 -- case merging will fail.)
326 --
327 -- Unfortunately, the choice can matter if there is a cycle. Consider the
328 -- following merge:
329 --
330 -- signature H where { type A = C; type B = A; data C }
331 -- signature H where { type A = (); data B; type C = B }
332 --
333 -- If we pick @type A = C@ as our representative, there will be
334 -- a cycle and merging will fail. But if we pick @type A = ()@ as
335 -- our representative, no cycle occurs, and we instead conclude
336 -- that all of the types are unit. So it seems that we either
337 -- (a) need a stronger acyclicity check which considers *all*
338 -- possible choices from a merge, or (b) we must find a selection
339 -- of declarations which is acyclic, and show that this is always
340 -- the "best" choice we could have made (ezyang conjectures this
341 -- is the case but does not have a proof). For now this is
342 -- not implemented.
343 --
344 -- It's worth noting that at the moment, a data constructor and a
345 -- type synonym are never compatible. Consider:
346 --
347 -- signature H where { type Int=C; type B = Int; data C = Int}
348 -- signature H where { export Prelude.Int; data B; type C = B; }
349 --
350 -- This will be rejected, because the reexported Int in the second
351 -- signature (a proper data type) is never considered equal to a
352 -- type synonym. Perhaps this should be relaxed, where a type synonym
353 -- in a signature is considered implemented by a data type declaration
354 -- which matches the reference of the type synonym.
355 typecheckIfacesForMerging :: Module -> [ModIface] -> IORef TypeEnv -> IfM lcl (TypeEnv, [ModDetails])
356 typecheckIfacesForMerging mod ifaces tc_env_var =
357 -- cannot be boot (False)
358 initIfaceLcl mod (text "typecheckIfacesForMerging") False $ do
359 ignore_prags <- goptM Opt_IgnoreInterfacePragmas
360 -- Build the initial environment
361 -- NB: Don't include dfuns here, because we don't want to
362 -- serialize them out. See Note [rnIfaceNeverExported] in RnModIface
363 -- NB: But coercions are OK, because they will have the right OccName.
364 let mk_decl_env decls
365 = mkOccEnv [ (getOccName decl, decl)
366 | decl <- decls
367 , case decl of
368 IfaceId { ifIdDetails = IfDFunId } -> False -- exclude DFuns
369 _ -> True ]
370 decl_envs = map (mk_decl_env . map snd . mi_decls) ifaces
371 :: [OccEnv IfaceDecl]
372 decl_env = foldl' mergeIfaceDecls emptyOccEnv decl_envs
373 :: OccEnv IfaceDecl
374 -- TODO: change loadDecls to accept w/o Fingerprint
375 names_w_things <- loadDecls ignore_prags (map (\x -> (fingerprint0, x))
376 (occEnvElts decl_env))
377 let global_type_env = mkNameEnv names_w_things
378 writeMutVar tc_env_var global_type_env
379
380 -- OK, now typecheck each ModIface using this environment
381 details <- forM ifaces $ \iface -> do
382 -- See Note [Resolving never-exported Names in TcIface]
383 type_env <- fixM $ \type_env -> do
384 setImplicitEnvM type_env $ do
385 decls <- loadDecls ignore_prags (mi_decls iface)
386 return (mkNameEnv decls)
387 -- But note that we use this type_env to typecheck references to DFun
388 -- in 'IfaceInst'
389 setImplicitEnvM type_env $ do
390 insts <- mapM tcIfaceInst (mi_insts iface)
391 fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
392 rules <- tcIfaceRules ignore_prags (mi_rules iface)
393 anns <- tcIfaceAnnotations (mi_anns iface)
394 vect_info <- tcIfaceVectInfo (mi_semantic_module iface) type_env (mi_vect_info iface)
395 exports <- ifaceExportNames (mi_exports iface)
396 complete_sigs <- tcIfaceCompleteSigs (mi_complete_sigs iface)
397 return $ ModDetails { md_types = type_env
398 , md_insts = insts
399 , md_fam_insts = fam_insts
400 , md_rules = rules
401 , md_anns = anns
402 , md_vect_info = vect_info
403 , md_exports = exports
404 , md_complete_sigs = complete_sigs
405 }
406 return (global_type_env, details)
407
408 -- | Typecheck a signature 'ModIface' under the assumption that we have
409 -- instantiated it under some implementation (recorded in 'mi_semantic_module')
410 -- and want to check if the implementation fills the signature.
411 --
412 -- This needs to operate slightly differently than 'typecheckIface'
413 -- because (1) we have a 'NameShape', from the exports of the
414 -- implementing module, which we will use to give our top-level
415 -- declarations the correct 'Name's even when the implementor
416 -- provided them with a reexport, and (2) we have to deal with
417 -- DFun silliness (see Note [rnIfaceNeverExported])
418 typecheckIfaceForInstantiate :: NameShape -> ModIface -> IfM lcl ModDetails
419 typecheckIfaceForInstantiate nsubst iface =
420 initIfaceLclWithSubst (mi_semantic_module iface)
421 (text "typecheckIfaceForInstantiate")
422 (mi_boot iface) nsubst $ do
423 ignore_prags <- goptM Opt_IgnoreInterfacePragmas
424 -- See Note [Resolving never-exported Names in TcIface]
425 type_env <- fixM $ \type_env -> do
426 setImplicitEnvM type_env $ do
427 decls <- loadDecls ignore_prags (mi_decls iface)
428 return (mkNameEnv decls)
429 -- See Note [rnIfaceNeverExported]
430 setImplicitEnvM type_env $ do
431 insts <- mapM tcIfaceInst (mi_insts iface)
432 fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
433 rules <- tcIfaceRules ignore_prags (mi_rules iface)
434 anns <- tcIfaceAnnotations (mi_anns iface)
435 vect_info <- tcIfaceVectInfo (mi_semantic_module iface) type_env (mi_vect_info iface)
436 exports <- ifaceExportNames (mi_exports iface)
437 complete_sigs <- tcIfaceCompleteSigs (mi_complete_sigs iface)
438 return $ ModDetails { md_types = type_env
439 , md_insts = insts
440 , md_fam_insts = fam_insts
441 , md_rules = rules
442 , md_anns = anns
443 , md_vect_info = vect_info
444 , md_exports = exports
445 , md_complete_sigs = complete_sigs
446 }
447
448 -- Note [Resolving never-exported Names in TcIface]
449 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
450 -- For the high-level overview, see
451 -- Note [Handling never-exported TyThings under Backpack]
452 --
453 -- As described in 'typecheckIfacesForMerging', the splendid innovation
454 -- of signature merging is to rewrite all Names in each of the signatures
455 -- we are merging together to a pre-merged structure; this is the key
456 -- ingredient that lets us solve some problems when merging type
457 -- synonyms.
458 --
459 -- However, when a 'Name' refers to a NON-exported entity, as is the
460 -- case with the DFun of a ClsInst, or a CoAxiom of a type family,
461 -- this strategy causes problems: if we pick one and rewrite all
462 -- references to a shared 'Name', we will accidentally fail to check
463 -- if the DFun or CoAxioms are compatible, as they will never be
464 -- checked--only exported entities are checked for compatibility,
465 -- and a non-exported TyThing is checked WHEN we are checking the
466 -- ClsInst or type family for compatibility in checkBootDeclM.
467 -- By virtue of the fact that everything's been pointed to the merged
468 -- declaration, you'll never notice there's a difference even if there
469 -- is one.
470 --
471 -- Fortunately, there are only a few places in the interface declarations
472 -- where this can occur, so we replace those calls with 'tcIfaceImplicit',
473 -- which will consult a local TypeEnv that records any never-exported
474 -- TyThings which we should wire up with.
475 --
476 -- Note that we actually knot-tie this local TypeEnv (the 'fixM'), because a
477 -- type family can refer to a coercion axiom, all of which are done in one go
478 -- when we typecheck 'mi_decls'. An alternate strategy would be to typecheck
479 -- coercions first before type families, but that seemed more fragile.
480 --
481
482 {-
483 ************************************************************************
484 * *
485 Type and class declarations
486 * *
487 ************************************************************************
488 -}
489
490 tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
491 -- Load the hi-boot iface for the module being compiled,
492 -- if it indeed exists in the transitive closure of imports
493 -- Return the ModDetails; Nothing if no hi-boot iface
494 tcHiBootIface hsc_src mod
495 | HsBootFile <- hsc_src -- Already compiling a hs-boot file
496 = return NoSelfBoot
497 | otherwise
498 = do { traceIf (text "loadHiBootInterface" <+> ppr mod)
499
500 ; mode <- getGhcMode
501 ; if not (isOneShot mode)
502 -- In --make and interactive mode, if this module has an hs-boot file
503 -- we'll have compiled it already, and it'll be in the HPT
504 --
505 -- We check wheher the interface is a *boot* interface.
506 -- It can happen (when using GHC from Visual Studio) that we
507 -- compile a module in TypecheckOnly mode, with a stable,
508 -- fully-populated HPT. In that case the boot interface isn't there
509 -- (it's been replaced by the mother module) so we can't check it.
510 -- And that's fine, because if M's ModInfo is in the HPT, then
511 -- it's been compiled once, and we don't need to check the boot iface
512 then do { hpt <- getHpt
513 ; case lookupHpt hpt (moduleName mod) of
514 Just info | mi_boot (hm_iface info)
515 -> mkSelfBootInfo (hm_iface info) (hm_details info)
516 _ -> return NoSelfBoot }
517 else do
518
519 -- OK, so we're in one-shot mode.
520 -- Re #9245, we always check if there is an hi-boot interface
521 -- to check consistency against, rather than just when we notice
522 -- that an hi-boot is necessary due to a circular import.
523 { read_result <- findAndReadIface
524 need (fst (splitModuleInsts mod)) mod
525 True -- Hi-boot file
526
527 ; case read_result of {
528 Succeeded (iface, _path) -> do { tc_iface <- initIfaceTcRn $ typecheckIface iface
529 ; mkSelfBootInfo iface tc_iface } ;
530 Failed err ->
531
532 -- There was no hi-boot file. But if there is circularity in
533 -- the module graph, there really should have been one.
534 -- Since we've read all the direct imports by now,
535 -- eps_is_boot will record if any of our imports mention the
536 -- current module, which either means a module loop (not
537 -- a SOURCE import) or that our hi-boot file has mysteriously
538 -- disappeared.
539 do { eps <- getEps
540 ; case lookupUFM (eps_is_boot eps) (moduleName mod) of
541 Nothing -> return NoSelfBoot -- The typical case
542
543 Just (_, False) -> failWithTc moduleLoop
544 -- Someone below us imported us!
545 -- This is a loop with no hi-boot in the way
546
547 Just (_mod, True) -> failWithTc (elaborate err)
548 -- The hi-boot file has mysteriously disappeared.
549 }}}}
550 where
551 need = text "Need the hi-boot interface for" <+> ppr mod
552 <+> text "to compare against the Real Thing"
553
554 moduleLoop = text "Circular imports: module" <+> quotes (ppr mod)
555 <+> text "depends on itself"
556
557 elaborate err = hang (text "Could not find hi-boot interface for" <+>
558 quotes (ppr mod) <> colon) 4 err
559
560
561 mkSelfBootInfo :: ModIface -> ModDetails -> TcRn SelfBootInfo
562 mkSelfBootInfo iface mds
563 = do -- NB: This is computed DIRECTLY from the ModIface rather
564 -- than from the ModDetails, so that we can query 'sb_tcs'
565 -- WITHOUT forcing the contents of the interface.
566 let tcs = map ifName
567 . filter isIfaceTyCon
568 . map snd
569 $ mi_decls iface
570 return $ SelfBoot { sb_mds = mds
571 , sb_tcs = mkNameSet tcs }
572 where
573 -- | Retuerns @True@ if, when you call 'tcIfaceDecl' on
574 -- this 'IfaceDecl', an ATyCon would be returned.
575 -- NB: This code assumes that a TyCon cannot be implicit.
576 isIfaceTyCon IfaceId{} = False
577 isIfaceTyCon IfaceData{} = True
578 isIfaceTyCon IfaceSynonym{} = True
579 isIfaceTyCon IfaceFamily{} = True
580 isIfaceTyCon IfaceClass{} = True
581 isIfaceTyCon IfaceAxiom{} = False
582 isIfaceTyCon IfacePatSyn{} = False
583
584 {-
585 ************************************************************************
586 * *
587 Type and class declarations
588 * *
589 ************************************************************************
590
591 When typechecking a data type decl, we *lazily* (via forkM) typecheck
592 the constructor argument types. This is in the hope that we may never
593 poke on those argument types, and hence may never need to load the
594 interface files for types mentioned in the arg types.
595
596 E.g.
597 data Foo.S = MkS Baz.T
598 Maybe we can get away without even loading the interface for Baz!
599
600 This is not just a performance thing. Suppose we have
601 data Foo.S = MkS Baz.T
602 data Baz.T = MkT Foo.S
603 (in different interface files, of course).
604 Now, first we load and typecheck Foo.S, and add it to the type envt.
605 If we do explore MkS's argument, we'll load and typecheck Baz.T.
606 If we explore MkT's argument we'll find Foo.S already in the envt.
607
608 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
609 typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
610 which isn't done yet.
611
612 All very cunning. However, there is a rather subtle gotcha which bit
613 me when developing this stuff. When we typecheck the decl for S, we
614 extend the type envt with S, MkS, and all its implicit Ids. Suppose
615 (a bug, but it happened) that the list of implicit Ids depended in
616 turn on the constructor arg types. Then the following sequence of
617 events takes place:
618 * we build a thunk <t> for the constructor arg tys
619 * we build a thunk for the extended type environment (depends on <t>)
620 * we write the extended type envt into the global EPS mutvar
621
622 Now we look something up in the type envt
623 * that pulls on <t>
624 * which reads the global type envt out of the global EPS mutvar
625 * but that depends in turn on <t>
626
627 It's subtle, because, it'd work fine if we typechecked the constructor args
628 eagerly -- they don't need the extended type envt. They just get the extended
629 type envt by accident, because they look at it later.
630
631 What this means is that the implicitTyThings MUST NOT DEPEND on any of
632 the forkM stuff.
633 -}
634
635 tcIfaceDecl :: Bool -- ^ True <=> discard IdInfo on IfaceId bindings
636 -> IfaceDecl
637 -> IfL TyThing
638 tcIfaceDecl = tc_iface_decl Nothing
639
640 tc_iface_decl :: Maybe Class -- ^ For associated type/data family declarations
641 -> Bool -- ^ True <=> discard IdInfo on IfaceId bindings
642 -> IfaceDecl
643 -> IfL TyThing
644 tc_iface_decl _ ignore_prags (IfaceId {ifName = name, ifType = iface_type,
645 ifIdDetails = details, ifIdInfo = info})
646 = do { ty <- tcIfaceType iface_type
647 ; details <- tcIdDetails ty details
648 ; info <- tcIdInfo ignore_prags name ty info
649 ; return (AnId (mkGlobalId details name ty info)) }
650
651 tc_iface_decl _ _ (IfaceData {ifName = tc_name,
652 ifCType = cType,
653 ifBinders = binders,
654 ifResKind = res_kind,
655 ifRoles = roles,
656 ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
657 ifCons = rdr_cons,
658 ifParent = mb_parent })
659 = bindIfaceTyConBinders_AT binders $ \ binders' -> do
660 { res_kind' <- tcIfaceType res_kind
661
662 ; tycon <- fixM $ \ tycon -> do
663 { stupid_theta <- tcIfaceCtxt ctxt
664 ; parent' <- tc_parent tc_name mb_parent
665 ; cons <- tcIfaceDataCons tc_name tycon binders' rdr_cons
666 ; return (mkAlgTyCon tc_name binders' res_kind'
667 roles cType stupid_theta
668 cons parent' gadt_syn) }
669 ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
670 ; return (ATyCon tycon) }
671 where
672 tc_parent :: Name -> IfaceTyConParent -> IfL AlgTyConFlav
673 tc_parent tc_name IfNoParent
674 = do { tc_rep_name <- newTyConRepName tc_name
675 ; return (VanillaAlgTyCon tc_rep_name) }
676 tc_parent _ (IfDataInstance ax_name _ arg_tys)
677 = do { ax <- tcIfaceCoAxiom ax_name
678 ; let fam_tc = coAxiomTyCon ax
679 ax_unbr = toUnbranchedAxiom ax
680 ; lhs_tys <- tcIfaceTcArgs arg_tys
681 ; return (DataFamInstTyCon ax_unbr fam_tc lhs_tys) }
682
683 tc_iface_decl _ _ (IfaceSynonym {ifName = tc_name,
684 ifRoles = roles,
685 ifSynRhs = rhs_ty,
686 ifBinders = binders,
687 ifResKind = res_kind })
688 = bindIfaceTyConBinders_AT binders $ \ binders' -> do
689 { res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
690 ; rhs <- forkM (mk_doc tc_name) $
691 tcIfaceType rhs_ty
692 ; let tycon = buildSynTyCon tc_name binders' res_kind' roles rhs
693 ; return (ATyCon tycon) }
694 where
695 mk_doc n = text "Type synonym" <+> ppr n
696
697 tc_iface_decl parent _ (IfaceFamily {ifName = tc_name,
698 ifFamFlav = fam_flav,
699 ifBinders = binders,
700 ifResKind = res_kind,
701 ifResVar = res, ifFamInj = inj })
702 = bindIfaceTyConBinders_AT binders $ \ binders' -> do
703 { res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
704 ; rhs <- forkM (mk_doc tc_name) $
705 tc_fam_flav tc_name fam_flav
706 ; res_name <- traverse (newIfaceName . mkTyVarOccFS) res
707 ; let tycon = mkFamilyTyCon tc_name binders' res_kind' res_name rhs parent inj
708 ; return (ATyCon tycon) }
709 where
710 mk_doc n = text "Type synonym" <+> ppr n
711
712 tc_fam_flav :: Name -> IfaceFamTyConFlav -> IfL FamTyConFlav
713 tc_fam_flav tc_name IfaceDataFamilyTyCon
714 = do { tc_rep_name <- newTyConRepName tc_name
715 ; return (DataFamilyTyCon tc_rep_name) }
716 tc_fam_flav _ IfaceOpenSynFamilyTyCon= return OpenSynFamilyTyCon
717 tc_fam_flav _ (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
718 = do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
719 ; return (ClosedSynFamilyTyCon ax) }
720 tc_fam_flav _ IfaceAbstractClosedSynFamilyTyCon
721 = return AbstractClosedSynFamilyTyCon
722 tc_fam_flav _ IfaceBuiltInSynFamTyCon
723 = pprPanic "tc_iface_decl"
724 (text "IfaceBuiltInSynFamTyCon in interface file")
725
726 tc_iface_decl _parent _ignore_prags
727 (IfaceClass {ifName = tc_name,
728 ifRoles = roles,
729 ifBinders = binders,
730 ifFDs = rdr_fds,
731 ifBody = IfAbstractClass})
732 = bindIfaceTyConBinders binders $ \ binders' -> do
733 { fds <- mapM tc_fd rdr_fds
734 ; cls <- buildClass tc_name binders' roles fds Nothing
735 ; return (ATyCon (classTyCon cls)) }
736
737 tc_iface_decl _parent ignore_prags
738 (IfaceClass {ifName = tc_name,
739 ifRoles = roles,
740 ifBinders = binders,
741 ifFDs = rdr_fds,
742 ifBody = IfConcreteClass {
743 ifClassCtxt = rdr_ctxt,
744 ifATs = rdr_ats, ifSigs = rdr_sigs,
745 ifMinDef = mindef_occ
746 }})
747 = bindIfaceTyConBinders binders $ \ binders' -> do
748 { traceIf (text "tc-iface-class1" <+> ppr tc_name)
749 ; ctxt <- mapM tc_sc rdr_ctxt
750 ; traceIf (text "tc-iface-class2" <+> ppr tc_name)
751 ; sigs <- mapM tc_sig rdr_sigs
752 ; fds <- mapM tc_fd rdr_fds
753 ; traceIf (text "tc-iface-class3" <+> ppr tc_name)
754 ; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
755 ; cls <- fixM $ \ cls -> do
756 { ats <- mapM (tc_at cls) rdr_ats
757 ; traceIf (text "tc-iface-class4" <+> ppr tc_name)
758 ; buildClass tc_name binders' roles fds (Just (ctxt, ats, sigs, mindef)) }
759 ; return (ATyCon (classTyCon cls)) }
760 where
761 tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
762 -- The *length* of the superclasses is used by buildClass, and hence must
763 -- not be inside the thunk. But the *content* maybe recursive and hence
764 -- must be lazy (via forkM). Example:
765 -- class C (T a) => D a where
766 -- data T a
767 -- Here the associated type T is knot-tied with the class, and
768 -- so we must not pull on T too eagerly. See Trac #5970
769
770 tc_sig :: IfaceClassOp -> IfL TcMethInfo
771 tc_sig (IfaceClassOp op_name rdr_ty dm)
772 = do { let doc = mk_op_doc op_name rdr_ty
773 ; op_ty <- forkM (doc <+> text "ty") $ tcIfaceType rdr_ty
774 -- Must be done lazily for just the same reason as the
775 -- type of a data con; to avoid sucking in types that
776 -- it mentions unless it's necessary to do so
777 ; dm' <- tc_dm doc dm
778 ; return (op_name, op_ty, dm') }
779
780 tc_dm :: SDoc
781 -> Maybe (DefMethSpec IfaceType)
782 -> IfL (Maybe (DefMethSpec (SrcSpan, Type)))
783 tc_dm _ Nothing = return Nothing
784 tc_dm _ (Just VanillaDM) = return (Just VanillaDM)
785 tc_dm doc (Just (GenericDM ty))
786 = do { -- Must be done lazily to avoid sucking in types
787 ; ty' <- forkM (doc <+> text "dm") $ tcIfaceType ty
788 ; return (Just (GenericDM (noSrcSpan, ty'))) }
789
790 tc_at cls (IfaceAT tc_decl if_def)
791 = do ATyCon tc <- tc_iface_decl (Just cls) ignore_prags tc_decl
792 mb_def <- case if_def of
793 Nothing -> return Nothing
794 Just def -> forkM (mk_at_doc tc) $
795 extendIfaceTyVarEnv (tyConTyVars tc) $
796 do { tc_def <- tcIfaceType def
797 ; return (Just (tc_def, noSrcSpan)) }
798 -- Must be done lazily in case the RHS of the defaults mention
799 -- the type constructor being defined here
800 -- e.g. type AT a; type AT b = AT [b] Trac #8002
801 return (ATI tc mb_def)
802
803 mk_sc_doc pred = text "Superclass" <+> ppr pred
804 mk_at_doc tc = text "Associated type" <+> ppr tc
805 mk_op_doc op_name op_ty = text "Class op" <+> sep [ppr op_name, ppr op_ty]
806
807 tc_iface_decl _ _ (IfaceAxiom { ifName = tc_name, ifTyCon = tc
808 , ifAxBranches = branches, ifRole = role })
809 = do { tc_tycon <- tcIfaceTyCon tc
810 ; tc_branches <- tc_ax_branches branches
811 ; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
812 , co_ax_name = tc_name
813 , co_ax_tc = tc_tycon
814 , co_ax_role = role
815 , co_ax_branches = manyBranches tc_branches
816 , co_ax_implicit = False }
817 ; return (ACoAxiom axiom) }
818
819 tc_iface_decl _ _ (IfacePatSyn{ ifName = name
820 , ifPatMatcher = if_matcher
821 , ifPatBuilder = if_builder
822 , ifPatIsInfix = is_infix
823 , ifPatUnivBndrs = univ_bndrs
824 , ifPatExBndrs = ex_bndrs
825 , ifPatProvCtxt = prov_ctxt
826 , ifPatReqCtxt = req_ctxt
827 , ifPatArgs = args
828 , ifPatTy = pat_ty
829 , ifFieldLabels = field_labels })
830 = do { traceIf (text "tc_iface_decl" <+> ppr name)
831 ; matcher <- tc_pr if_matcher
832 ; builder <- fmapMaybeM tc_pr if_builder
833 ; bindIfaceForAllBndrs univ_bndrs $ \univ_tvs -> do
834 { bindIfaceForAllBndrs ex_bndrs $ \ex_tvs -> do
835 { patsyn <- forkM (mk_doc name) $
836 do { prov_theta <- tcIfaceCtxt prov_ctxt
837 ; req_theta <- tcIfaceCtxt req_ctxt
838 ; pat_ty <- tcIfaceType pat_ty
839 ; arg_tys <- mapM tcIfaceType args
840 ; return $ buildPatSyn name is_infix matcher builder
841 (univ_tvs, req_theta)
842 (ex_tvs, prov_theta)
843 arg_tys pat_ty field_labels }
844 ; return $ AConLike . PatSynCon $ patsyn }}}
845 where
846 mk_doc n = text "Pattern synonym" <+> ppr n
847 tc_pr :: (IfExtName, Bool) -> IfL (Id, Bool)
848 tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
849 ; return (id, b) }
850
851 tc_fd :: FunDep IfLclName -> IfL (FunDep TyVar)
852 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
853 ; tvs2' <- mapM tcIfaceTyVar tvs2
854 ; return (tvs1', tvs2') }
855
856 tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
857 tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
858
859 tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
860 tc_ax_branch prev_branches
861 (IfaceAxBranch { ifaxbTyVars = tv_bndrs, ifaxbCoVars = cv_bndrs
862 , ifaxbLHS = lhs, ifaxbRHS = rhs
863 , ifaxbRoles = roles, ifaxbIncomps = incomps })
864 = bindIfaceTyConBinders_AT
865 (map (\b -> TvBndr b (NamedTCB Inferred)) tv_bndrs) $ \ tvs ->
866 -- The _AT variant is needed here; see Note [CoAxBranch type variables] in CoAxiom
867 bindIfaceIds cv_bndrs $ \ cvs -> do
868 { tc_lhs <- tcIfaceTcArgs lhs
869 ; tc_rhs <- tcIfaceType rhs
870 ; let br = CoAxBranch { cab_loc = noSrcSpan
871 , cab_tvs = binderVars tvs
872 , cab_cvs = cvs
873 , cab_lhs = tc_lhs
874 , cab_roles = roles
875 , cab_rhs = tc_rhs
876 , cab_incomps = map (prev_branches `getNth`) incomps }
877 ; return (prev_branches ++ [br]) }
878
879 tcIfaceDataCons :: Name -> TyCon -> [TyConBinder] -> IfaceConDecls -> IfL AlgTyConRhs
880 tcIfaceDataCons tycon_name tycon tc_tybinders if_cons
881 = case if_cons of
882 IfAbstractTyCon -> return AbstractTyCon
883 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
884 ; return (mkDataTyConRhs data_cons) }
885 IfNewTyCon con -> do { data_con <- tc_con_decl con
886 ; mkNewTyConRhs tycon_name tycon data_con }
887 where
888 univ_tv_bndrs :: [TyVarBinder]
889 univ_tv_bndrs = mkDataConUnivTyVarBinders tc_tybinders
890
891 tc_con_decl (IfCon { ifConInfix = is_infix,
892 ifConExTvs = ex_bndrs,
893 ifConName = dc_name,
894 ifConCtxt = ctxt, ifConEqSpec = spec,
895 ifConArgTys = args, ifConFields = lbl_names,
896 ifConStricts = if_stricts,
897 ifConSrcStricts = if_src_stricts})
898 = -- Universally-quantified tyvars are shared with
899 -- parent TyCon, and are already in scope
900 bindIfaceForAllBndrs ex_bndrs $ \ ex_tv_bndrs -> do
901 { traceIf (text "Start interface-file tc_con_decl" <+> ppr dc_name)
902
903 -- Read the context and argument types, but lazily for two reasons
904 -- (a) to avoid looking tugging on a recursive use of
905 -- the type itself, which is knot-tied
906 -- (b) to avoid faulting in the component types unless
907 -- they are really needed
908 ; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc dc_name) $
909 do { eq_spec <- tcIfaceEqSpec spec
910 ; theta <- tcIfaceCtxt ctxt
911 ; arg_tys <- mapM tcIfaceType args
912 ; stricts <- mapM tc_strict if_stricts
913 -- The IfBang field can mention
914 -- the type itself; hence inside forkM
915 ; return (eq_spec, theta, arg_tys, stricts) }
916
917 -- Remember, tycon is the representation tycon
918 ; let orig_res_ty = mkFamilyTyConApp tycon
919 (substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec))
920 (binderVars tc_tybinders))
921
922 ; prom_rep_name <- newTyConRepName dc_name
923
924 ; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr dc_name))
925 dc_name is_infix prom_rep_name
926 (map src_strict if_src_stricts)
927 (Just stricts)
928 -- Pass the HsImplBangs (i.e. final
929 -- decisions) to buildDataCon; it'll use
930 -- these to guide the construction of a
931 -- worker.
932 -- See Note [Bangs on imported data constructors] in MkId
933 lbl_names
934 univ_tv_bndrs ex_tv_bndrs
935 eq_spec theta
936 arg_tys orig_res_ty tycon
937 ; traceIf (text "Done interface-file tc_con_decl" <+> ppr dc_name)
938 ; return con }
939 mk_doc con_name = text "Constructor" <+> ppr con_name
940
941 tc_strict :: IfaceBang -> IfL HsImplBang
942 tc_strict IfNoBang = return (HsLazy)
943 tc_strict IfStrict = return (HsStrict)
944 tc_strict IfUnpack = return (HsUnpack Nothing)
945 tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
946 ; return (HsUnpack (Just co)) }
947
948 src_strict :: IfaceSrcBang -> HsSrcBang
949 src_strict (IfSrcBang unpk bang) = HsSrcBang NoSourceText unpk bang
950
951 tcIfaceEqSpec :: IfaceEqSpec -> IfL [EqSpec]
952 tcIfaceEqSpec spec
953 = mapM do_item spec
954 where
955 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
956 ; ty <- tcIfaceType if_ty
957 ; return (mkEqSpec tv ty) }
958
959 {-
960 Note [Synonym kind loop]
961 ~~~~~~~~~~~~~~~~~~~~~~~~
962 Notice that we eagerly grab the *kind* from the interface file, but
963 build a forkM thunk for the *rhs* (and family stuff). To see why,
964 consider this (Trac #2412)
965
966 M.hs: module M where { import X; data T = MkT S }
967 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
968 M.hs-boot: module M where { data T }
969
970 When kind-checking M.hs we need S's kind. But we do not want to
971 find S's kind from (typeKind S-rhs), because we don't want to look at
972 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
973 be defined, and we must not do that until we've finished with M.T.
974
975 Solution: record S's kind in the interface file; now we can safely
976 look at it.
977
978 ************************************************************************
979 * *
980 Instances
981 * *
982 ************************************************************************
983 -}
984
985 tcIfaceInst :: IfaceClsInst -> IfL ClsInst
986 tcIfaceInst (IfaceClsInst { ifDFun = dfun_name, ifOFlag = oflag
987 , ifInstCls = cls, ifInstTys = mb_tcs
988 , ifInstOrph = orph })
989 = do { dfun <- forkM (text "Dict fun" <+> ppr dfun_name) $
990 fmap tyThingId (tcIfaceImplicit dfun_name)
991 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
992 ; return (mkImportedInstance cls mb_tcs' dfun_name dfun oflag orph) }
993
994 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
995 tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
996 , ifFamInstAxiom = axiom_name } )
997 = do { axiom' <- forkM (text "Axiom" <+> ppr axiom_name) $
998 tcIfaceCoAxiom axiom_name
999 -- will panic if branched, but that's OK
1000 ; let axiom'' = toUnbranchedAxiom axiom'
1001 mb_tcs' = map (fmap ifaceTyConName) mb_tcs
1002 ; return (mkImportedFamInst fam mb_tcs' axiom'') }
1003
1004 {-
1005 ************************************************************************
1006 * *
1007 Rules
1008 * *
1009 ************************************************************************
1010
1011 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
1012 are in the type environment. However, remember that typechecking a Rule may
1013 (as a side effect) augment the type envt, and so we may need to iterate the process.
1014 -}
1015
1016 tcIfaceRules :: Bool -- True <=> ignore rules
1017 -> [IfaceRule]
1018 -> IfL [CoreRule]
1019 tcIfaceRules ignore_prags if_rules
1020 | ignore_prags = return []
1021 | otherwise = mapM tcIfaceRule if_rules
1022
1023 tcIfaceRule :: IfaceRule -> IfL CoreRule
1024 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
1025 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
1026 ifRuleAuto = auto, ifRuleOrph = orph })
1027 = do { ~(bndrs', args', rhs') <-
1028 -- Typecheck the payload lazily, in the hope it'll never be looked at
1029 forkM (text "Rule" <+> pprRuleName name) $
1030 bindIfaceBndrs bndrs $ \ bndrs' ->
1031 do { args' <- mapM tcIfaceExpr args
1032 ; rhs' <- tcIfaceExpr rhs
1033 ; return (bndrs', args', rhs') }
1034 ; let mb_tcs = map ifTopFreeName args
1035 ; this_mod <- getIfModule
1036 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
1037 ru_bndrs = bndrs', ru_args = args',
1038 ru_rhs = occurAnalyseExpr rhs',
1039 ru_rough = mb_tcs,
1040 ru_origin = this_mod,
1041 ru_orphan = orph,
1042 ru_auto = auto,
1043 ru_local = False }) } -- An imported RULE is never for a local Id
1044 -- or, even if it is (module loop, perhaps)
1045 -- we'll just leave it in the non-local set
1046 where
1047 -- This function *must* mirror exactly what Rules.roughTopNames does
1048 -- We could have stored the ru_rough field in the iface file
1049 -- but that would be redundant, I think.
1050 -- The only wrinkle is that we must not be deceived by
1051 -- type synonyms at the top of a type arg. Since
1052 -- we can't tell at this point, we are careful not
1053 -- to write them out in coreRuleToIfaceRule
1054 ifTopFreeName :: IfaceExpr -> Maybe Name
1055 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
1056 ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (tcArgsIfaceTypes ts)))
1057 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
1058 ifTopFreeName (IfaceExt n) = Just n
1059 ifTopFreeName _ = Nothing
1060
1061 {-
1062 ************************************************************************
1063 * *
1064 Annotations
1065 * *
1066 ************************************************************************
1067 -}
1068
1069 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
1070 tcIfaceAnnotations = mapM tcIfaceAnnotation
1071
1072 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
1073 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
1074 target' <- tcIfaceAnnTarget target
1075 return $ Annotation {
1076 ann_target = target',
1077 ann_value = serialized
1078 }
1079
1080 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
1081 tcIfaceAnnTarget (NamedTarget occ) = do
1082 name <- lookupIfaceTop occ
1083 return $ NamedTarget name
1084 tcIfaceAnnTarget (ModuleTarget mod) = do
1085 return $ ModuleTarget mod
1086
1087 {-
1088 ************************************************************************
1089 * *
1090 Complete Match Pragmas
1091 * *
1092 ************************************************************************
1093 -}
1094
1095 tcIfaceCompleteSigs :: [IfaceCompleteMatch] -> IfL [CompleteMatch]
1096 tcIfaceCompleteSigs = mapM tcIfaceCompleteSig
1097
1098 tcIfaceCompleteSig :: IfaceCompleteMatch -> IfL CompleteMatch
1099 tcIfaceCompleteSig cm@(IfaceCompleteMatch ms t) =
1100 forkM (text "COMPLETE" <+> ppr cm) $
1101 CompleteMatch <$> mapM tcIfaceConLike ms <*> tcIfaceTyConByName t
1102
1103 {-
1104 ************************************************************************
1105 * *
1106 Vectorisation information
1107 * *
1108 ************************************************************************
1109 -}
1110
1111 -- We need access to the type environment as we need to look up information about type constructors
1112 -- (i.e., their data constructors and whether they are class type constructors). If a vectorised
1113 -- type constructor or class is defined in the same module as where it is vectorised, we cannot
1114 -- look that information up from the type constructor that we obtained via a 'forkM'ed
1115 -- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
1116 -- and again and again...
1117 --
1118 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
1119 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
1120 { ifaceVectInfoVar = vars
1121 , ifaceVectInfoTyCon = tycons
1122 , ifaceVectInfoTyConReuse = tyconsReuse
1123 , ifaceVectInfoParallelVars = parallelVars
1124 , ifaceVectInfoParallelTyCons = parallelTyCons
1125 })
1126 = do { let parallelTyConsSet = mkNameSet parallelTyCons
1127 ; vVars <- mapM vectVarMapping vars
1128 ; let varsSet = mkVarSet (map fst vVars)
1129 ; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
1130 ; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
1131 ; vParallelVars <- mapM vectVar parallelVars
1132 ; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
1133 ; return $ VectInfo
1134 { vectInfoVar = mkDVarEnv vVars `extendDVarEnvList` concat vScSels
1135 , vectInfoTyCon = mkNameEnv vTyCons
1136 , vectInfoDataCon = mkNameEnv (concat vDataCons)
1137 , vectInfoParallelVars = mkDVarSet vParallelVars
1138 , vectInfoParallelTyCons = parallelTyConsSet
1139 }
1140 }
1141 where
1142 vectVarMapping name
1143 = do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectOcc name)
1144 ; var <- forkM (text "vect var" <+> ppr name) $
1145 tcIfaceExtId name
1146 ; vVar <- forkM (text "vect vVar [mod =" <+>
1147 ppr mod <> text "; nameModule =" <+>
1148 ppr (nameModule name) <> text "]" <+> ppr vName) $
1149 tcIfaceExtId vName
1150 ; return (var, (var, vVar))
1151 }
1152 -- where
1153 -- lookupLocalOrExternalId name
1154 -- = do { let mb_id = lookupTypeEnv typeEnv name
1155 -- ; case mb_id of
1156 -- -- id is local
1157 -- Just (AnId id) -> return id
1158 -- -- name is not an Id => internal inconsistency
1159 -- Just _ -> notAnIdErr
1160 -- -- Id is external
1161 -- Nothing -> tcIfaceExtId name
1162 -- }
1163 --
1164 -- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
1165
1166 vectVar name
1167 = forkM (text "vect scalar var" <+> ppr name) $
1168 tcIfaceExtId name
1169
1170 vectTyConVectMapping vars name
1171 = do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectTyConOcc name)
1172 ; vectTyConMapping vars name vName
1173 }
1174
1175 vectTyConReuseMapping vars name
1176 = vectTyConMapping vars name name
1177
1178 vectTyConMapping vars name vName
1179 = do { tycon <- lookupLocalOrExternalTyCon name
1180 ; vTycon <- forkM (text "vTycon of" <+> ppr vName) $
1181 lookupLocalOrExternalTyCon vName
1182
1183 -- Map the data constructors of the original type constructor to those of the
1184 -- vectorised type constructor /unless/ the type constructor was vectorised
1185 -- abstractly; if it was vectorised abstractly, the workers of its data constructors
1186 -- do not appear in the set of vectorised variables.
1187 --
1188 -- NB: This is lazy! We don't pull at the type constructors before we actually use
1189 -- the data constructor mapping.
1190 ; let isAbstract | isClassTyCon tycon = False
1191 | datacon:_ <- tyConDataCons tycon
1192 = not $ dataConWrapId datacon `elemVarSet` vars
1193 | otherwise = True
1194 vDataCons | isAbstract = []
1195 | otherwise = [ (dataConName datacon, (datacon, vDatacon))
1196 | (datacon, vDatacon) <- zip (tyConDataCons tycon)
1197 (tyConDataCons vTycon)
1198 ]
1199
1200 -- Map the (implicit) superclass and methods selectors as they don't occur in
1201 -- the var map.
1202 vScSels | Just cls <- tyConClass_maybe tycon
1203 , Just vCls <- tyConClass_maybe vTycon
1204 = [ (sel, (sel, vSel))
1205 | (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
1206 ]
1207 | otherwise
1208 = []
1209
1210 ; return ( (name, (tycon, vTycon)) -- (T, T_v)
1211 , vDataCons -- list of (Ci, Ci_v)
1212 , vScSels -- list of (seli, seli_v)
1213 )
1214 }
1215 where
1216 -- we need a fully defined version of the type constructor to be able to extract
1217 -- its data constructors etc.
1218 lookupLocalOrExternalTyCon name
1219 = do { let mb_tycon = lookupTypeEnv typeEnv name
1220 ; case mb_tycon of
1221 -- tycon is local
1222 Just (ATyCon tycon) -> return tycon
1223 -- name is not a tycon => internal inconsistency
1224 Just _ -> notATyConErr
1225 -- tycon is external
1226 Nothing -> tcIfaceTyConByName name
1227 }
1228
1229 notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
1230
1231 {-
1232 ************************************************************************
1233 * *
1234 Types
1235 * *
1236 ************************************************************************
1237 -}
1238
1239 tcIfaceType :: IfaceType -> IfL Type
1240 tcIfaceType = go
1241 where
1242 go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
1243 go (IfaceFreeTyVar n) = pprPanic "tcIfaceType:IfaceFreeTyVar" (ppr n)
1244 go (IfaceAppTy t1 t2) = AppTy <$> go t1 <*> go t2
1245 go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
1246 go (IfaceFunTy t1 t2) = FunTy <$> go t1 <*> go t2
1247 go (IfaceDFunTy t1 t2) = FunTy <$> go t1 <*> go t2
1248 go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
1249 go (IfaceTyConApp tc tks)
1250 = do { tc' <- tcIfaceTyCon tc
1251 ; tks' <- mapM go (tcArgsIfaceTypes tks)
1252 ; return (mkTyConApp tc' tks') }
1253 go (IfaceForAllTy bndr t)
1254 = bindIfaceForAllBndr bndr $ \ tv' vis ->
1255 ForAllTy (TvBndr tv' vis) <$> go t
1256 go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
1257 go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
1258
1259 tcIfaceTupleTy :: TupleSort -> IsPromoted -> IfaceTcArgs -> IfL Type
1260 tcIfaceTupleTy sort is_promoted args
1261 = do { args' <- tcIfaceTcArgs args
1262 ; let arity = length args'
1263 ; base_tc <- tcTupleTyCon True sort arity
1264 ; case is_promoted of
1265 IsNotPromoted
1266 -> return (mkTyConApp base_tc args')
1267
1268 IsPromoted
1269 -> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
1270 kind_args = map typeKind args'
1271 ; return (mkTyConApp tc (kind_args ++ args')) } }
1272
1273 -- See Note [Unboxed tuple RuntimeRep vars] in TyCon
1274 tcTupleTyCon :: Bool -- True <=> typechecking a *type* (vs. an expr)
1275 -> TupleSort
1276 -> Arity -- the number of args. *not* the tuple arity.
1277 -> IfL TyCon
1278 tcTupleTyCon in_type sort arity
1279 = case sort of
1280 ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
1281 ; return (tyThingTyCon thing) }
1282 BoxedTuple -> return (tupleTyCon Boxed arity)
1283 UnboxedTuple -> return (tupleTyCon Unboxed arity')
1284 where arity' | in_type = arity `div` 2
1285 | otherwise = arity
1286 -- in expressions, we only have term args
1287
1288 tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
1289 tcIfaceTcArgs = mapM tcIfaceType . tcArgsIfaceTypes
1290
1291 -----------------------------------------
1292 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
1293 tcIfaceCtxt sts = mapM tcIfaceType sts
1294
1295 -----------------------------------------
1296 tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
1297 tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
1298 tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
1299
1300 {-
1301 %************************************************************************
1302 %* *
1303 Coercions
1304 * *
1305 ************************************************************************
1306 -}
1307
1308 tcIfaceCo :: IfaceCoercion -> IfL Coercion
1309 tcIfaceCo = go
1310 where
1311 go (IfaceReflCo r t) = Refl r <$> tcIfaceType t
1312 go (IfaceFunCo r c1 c2) = mkFunCo r <$> go c1 <*> go c2
1313 go (IfaceTyConAppCo r tc cs)
1314 = TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
1315 go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
1316 go (IfaceForAllCo tv k c) = do { k' <- go k
1317 ; bindIfaceTyVar tv $ \ tv' ->
1318 ForAllCo tv' k' <$> go c }
1319 go (IfaceCoVarCo n) = CoVarCo <$> go_var n
1320 go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
1321 go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
1322 <*> tcIfaceType t1 <*> tcIfaceType t2
1323 go (IfaceSymCo c) = SymCo <$> go c
1324 go (IfaceTransCo c1 c2) = TransCo <$> go c1
1325 <*> go c2
1326 go (IfaceInstCo c1 t2) = InstCo <$> go c1
1327 <*> go t2
1328 go (IfaceNthCo d c) = NthCo d <$> go c
1329 go (IfaceLRCo lr c) = LRCo lr <$> go c
1330 go (IfaceCoherenceCo c1 c2) = CoherenceCo <$> go c1
1331 <*> go c2
1332 go (IfaceKindCo c) = KindCo <$> go c
1333 go (IfaceSubCo c) = SubCo <$> go c
1334 go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> go_axiom_rule ax
1335 <*> mapM go cos
1336
1337 go_var :: FastString -> IfL CoVar
1338 go_var = tcIfaceLclId
1339
1340 go_axiom_rule :: FastString -> IfL CoAxiomRule
1341 go_axiom_rule n =
1342 case Map.lookup n typeNatCoAxiomRules of
1343 Just ax -> return ax
1344 _ -> pprPanic "go_axiom_rule" (ppr n)
1345
1346 tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
1347 tcIfaceUnivCoProv IfaceUnsafeCoerceProv = return UnsafeCoerceProv
1348 tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
1349 tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
1350 tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
1351 tcIfaceUnivCoProv (IfaceHoleProv _) =
1352 pprPanic "tcIfaceUnivCoProv" (text "holes can't occur in interface files")
1353
1354 {-
1355 ************************************************************************
1356 * *
1357 Core
1358 * *
1359 ************************************************************************
1360 -}
1361
1362 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
1363 tcIfaceExpr (IfaceType ty)
1364 = Type <$> tcIfaceType ty
1365
1366 tcIfaceExpr (IfaceCo co)
1367 = Coercion <$> tcIfaceCo co
1368
1369 tcIfaceExpr (IfaceCast expr co)
1370 = Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
1371
1372 tcIfaceExpr (IfaceLcl name)
1373 = Var <$> tcIfaceLclId name
1374
1375 tcIfaceExpr (IfaceExt gbl)
1376 = Var <$> tcIfaceExtId gbl
1377
1378 tcIfaceExpr (IfaceLit lit)
1379 = do lit' <- tcIfaceLit lit
1380 return (Lit lit')
1381
1382 tcIfaceExpr (IfaceFCall cc ty) = do
1383 ty' <- tcIfaceType ty
1384 u <- newUnique
1385 dflags <- getDynFlags
1386 return (Var (mkFCallId dflags u cc ty'))
1387
1388 tcIfaceExpr (IfaceTuple sort args)
1389 = do { args' <- mapM tcIfaceExpr args
1390 ; tc <- tcTupleTyCon False sort arity
1391 ; let con_tys = map exprType args'
1392 some_con_args = map Type con_tys ++ args'
1393 con_args = case sort of
1394 UnboxedTuple -> map (Type . getRuntimeRep "tcIfaceExpr") con_tys ++ some_con_args
1395 _ -> some_con_args
1396 -- Put the missing type arguments back in
1397 con_id = dataConWorkId (tyConSingleDataCon tc)
1398 ; return (mkApps (Var con_id) con_args) }
1399 where
1400 arity = length args
1401
1402 tcIfaceExpr (IfaceLam (bndr, os) body)
1403 = bindIfaceBndr bndr $ \bndr' ->
1404 Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
1405 where
1406 tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
1407 tcIfaceOneShot _ b = b
1408
1409 tcIfaceExpr (IfaceApp fun arg)
1410 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
1411
1412 tcIfaceExpr (IfaceECase scrut ty)
1413 = do { scrut' <- tcIfaceExpr scrut
1414 ; ty' <- tcIfaceType ty
1415 ; return (castBottomExpr scrut' ty') }
1416
1417 tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
1418 scrut' <- tcIfaceExpr scrut
1419 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
1420 let
1421 scrut_ty = exprType scrut'
1422 case_bndr' = mkLocalIdOrCoVar case_bndr_name scrut_ty
1423 tc_app = splitTyConApp scrut_ty
1424 -- NB: Won't always succeed (polymorphic case)
1425 -- but won't be demanded in those cases
1426 -- NB: not tcSplitTyConApp; we are looking at Core here
1427 -- look through non-rec newtypes to find the tycon that
1428 -- corresponds to the datacon in this case alternative
1429
1430 extendIfaceIdEnv [case_bndr'] $ do
1431 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
1432 return (Case scrut' case_bndr' (coreAltsType alts') alts')
1433
1434 tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info ji) rhs) body)
1435 = do { name <- newIfaceName (mkVarOccFS fs)
1436 ; ty' <- tcIfaceType ty
1437 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1438 name ty' info
1439 ; let id = mkLocalIdOrCoVarWithInfo name ty' id_info
1440 `asJoinId_maybe` tcJoinInfo ji
1441 ; rhs' <- tcIfaceExpr rhs
1442 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
1443 ; return (Let (NonRec id rhs') body') }
1444
1445 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
1446 = do { ids <- mapM tc_rec_bndr (map fst pairs)
1447 ; extendIfaceIdEnv ids $ do
1448 { pairs' <- zipWithM tc_pair pairs ids
1449 ; body' <- tcIfaceExpr body
1450 ; return (Let (Rec pairs') body') } }
1451 where
1452 tc_rec_bndr (IfLetBndr fs ty _ ji)
1453 = do { name <- newIfaceName (mkVarOccFS fs)
1454 ; ty' <- tcIfaceType ty
1455 ; return (mkLocalIdOrCoVar name ty' `asJoinId_maybe` tcJoinInfo ji) }
1456 tc_pair (IfLetBndr _ _ info _, rhs) id
1457 = do { rhs' <- tcIfaceExpr rhs
1458 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1459 (idName id) (idType id) info
1460 ; return (setIdInfo id id_info, rhs') }
1461
1462 tcIfaceExpr (IfaceTick tickish expr) = do
1463 expr' <- tcIfaceExpr expr
1464 -- If debug flag is not set: Ignore source notes
1465 dbgLvl <- fmap debugLevel getDynFlags
1466 case tickish of
1467 IfaceSource{} | dbgLvl > 0
1468 -> return expr'
1469 _otherwise -> do
1470 tickish' <- tcIfaceTickish tickish
1471 return (Tick tickish' expr')
1472
1473 -------------------------
1474 tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
1475 tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
1476 tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
1477 tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
1478
1479 -------------------------
1480 tcIfaceLit :: Literal -> IfL Literal
1481 -- Integer literals deserialise to (LitInteger i <error thunk>)
1482 -- so tcIfaceLit just fills in the type.
1483 -- See Note [Integer literals] in Literal
1484 tcIfaceLit (LitInteger i _)
1485 = do t <- tcIfaceTyConByName integerTyConName
1486 return (mkLitInteger i (mkTyConTy t))
1487 tcIfaceLit lit = return lit
1488
1489 -------------------------
1490 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
1491 -> (IfaceConAlt, [FastString], IfaceExpr)
1492 -> IfL (AltCon, [TyVar], CoreExpr)
1493 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
1494 = ASSERT( null names ) do
1495 rhs' <- tcIfaceExpr rhs
1496 return (DEFAULT, [], rhs')
1497
1498 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
1499 = ASSERT( null names ) do
1500 lit' <- tcIfaceLit lit
1501 rhs' <- tcIfaceExpr rhs
1502 return (LitAlt lit', [], rhs')
1503
1504 -- A case alternative is made quite a bit more complicated
1505 -- by the fact that we omit type annotations because we can
1506 -- work them out. True enough, but its not that easy!
1507 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
1508 = do { con <- tcIfaceDataCon data_occ
1509 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
1510 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
1511 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
1512
1513 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
1514 -> IfL (AltCon, [TyVar], CoreExpr)
1515 tcIfaceDataAlt con inst_tys arg_strs rhs
1516 = do { us <- newUniqueSupply
1517 ; let uniqs = uniqsFromSupply us
1518 ; let (ex_tvs, arg_ids)
1519 = dataConRepFSInstPat arg_strs uniqs con inst_tys
1520
1521 ; rhs' <- extendIfaceEnvs ex_tvs $
1522 extendIfaceIdEnv arg_ids $
1523 tcIfaceExpr rhs
1524 ; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
1525
1526 {-
1527 ************************************************************************
1528 * *
1529 IdInfo
1530 * *
1531 ************************************************************************
1532 -}
1533
1534 tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
1535 tcIdDetails _ IfVanillaId = return VanillaId
1536 tcIdDetails ty IfDFunId
1537 = return (DFunId (isNewTyCon (classTyCon cls)))
1538 where
1539 (_, _, cls, _) = tcSplitDFunTy ty
1540
1541 tcIdDetails _ (IfRecSelId tc naughty)
1542 = do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
1543 (fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
1544 tc
1545 ; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
1546 where
1547 tyThingPatSyn (AConLike (PatSynCon ps)) = ps
1548 tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
1549
1550 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
1551 tcIdInfo ignore_prags name ty info = do
1552 lcl_env <- getLclEnv
1553 -- Set the CgInfo to something sensible but uninformative before
1554 -- we start; default assumption is that it has CAFs
1555 let init_info | if_boot lcl_env = vanillaIdInfo `setUnfoldingInfo` BootUnfolding
1556 | otherwise = vanillaIdInfo
1557 if ignore_prags
1558 then return init_info
1559 else case info of
1560 NoInfo -> return init_info
1561 HasInfo info -> foldlM tcPrag init_info info
1562 where
1563 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
1564 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
1565 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
1566 tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
1567 tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
1568 tcPrag info HsLevity = return (info `setNeverLevPoly` ty)
1569
1570 -- The next two are lazy, so they don't transitively suck stuff in
1571 tcPrag info (HsUnfold lb if_unf)
1572 = do { unf <- tcUnfolding name ty info if_unf
1573 ; let info1 | lb = info `setOccInfo` strongLoopBreaker
1574 | otherwise = info
1575 ; return (info1 `setUnfoldingInfo` unf) }
1576
1577 tcJoinInfo :: IfaceJoinInfo -> Maybe JoinArity
1578 tcJoinInfo (IfaceJoinPoint ar) = Just ar
1579 tcJoinInfo IfaceNotJoinPoint = Nothing
1580
1581 tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
1582 tcUnfolding name _ info (IfCoreUnfold stable if_expr)
1583 = do { dflags <- getDynFlags
1584 ; mb_expr <- tcPragExpr name if_expr
1585 ; let unf_src | stable = InlineStable
1586 | otherwise = InlineRhs
1587 ; return $ case mb_expr of
1588 Nothing -> NoUnfolding
1589 Just expr -> mkUnfolding dflags unf_src
1590 True {- Top level -}
1591 (isBottomingSig strict_sig)
1592 expr
1593 }
1594 where
1595 -- Strictness should occur before unfolding!
1596 strict_sig = strictnessInfo info
1597 tcUnfolding name _ _ (IfCompulsory if_expr)
1598 = do { mb_expr <- tcPragExpr name if_expr
1599 ; return (case mb_expr of
1600 Nothing -> NoUnfolding
1601 Just expr -> mkCompulsoryUnfolding expr) }
1602
1603 tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
1604 = do { mb_expr <- tcPragExpr name if_expr
1605 ; return (case mb_expr of
1606 Nothing -> NoUnfolding
1607 Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
1608 where
1609 guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
1610
1611 tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
1612 = bindIfaceBndrs bs $ \ bs' ->
1613 do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
1614 ; return (case mb_ops1 of
1615 Nothing -> noUnfolding
1616 Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
1617 where
1618 doc = text "Class ops for dfun" <+> ppr name
1619 (_, _, cls, _) = tcSplitDFunTy dfun_ty
1620
1621 {-
1622 For unfoldings we try to do the job lazily, so that we never type check
1623 an unfolding that isn't going to be looked at.
1624 -}
1625
1626 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
1627 tcPragExpr name expr
1628 = forkM_maybe doc $ do
1629 core_expr' <- tcIfaceExpr expr
1630
1631 -- Check for type consistency in the unfolding
1632 whenGOptM Opt_DoCoreLinting $ do
1633 in_scope <- get_in_scope
1634 dflags <- getDynFlags
1635 case lintUnfolding dflags noSrcLoc in_scope core_expr' of
1636 Nothing -> return ()
1637 Just fail_msg -> do { mod <- getIfModule
1638 ; pprPanic "Iface Lint failure"
1639 (vcat [ text "In interface for" <+> ppr mod
1640 , hang doc 2 fail_msg
1641 , ppr name <+> equals <+> ppr core_expr'
1642 , text "Iface expr =" <+> ppr expr ]) }
1643 return core_expr'
1644 where
1645 doc = text "Unfolding of" <+> ppr name
1646
1647 get_in_scope :: IfL VarSet -- Totally disgusting; but just for linting
1648 get_in_scope
1649 = do { (gbl_env, lcl_env) <- getEnvs
1650 ; rec_ids <- case if_rec_types gbl_env of
1651 Nothing -> return []
1652 Just (_, get_env) -> do
1653 { type_env <- setLclEnv () get_env
1654 ; return (typeEnvIds type_env) }
1655 ; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
1656 bindingsVars (if_id_env lcl_env) `unionVarSet`
1657 mkVarSet rec_ids) }
1658
1659 bindingsVars :: FastStringEnv Var -> VarSet
1660 bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
1661 -- It's OK to use nonDetEltsUFM here because we immediately forget
1662 -- the ordering by creating a set
1663
1664 {-
1665 ************************************************************************
1666 * *
1667 Getting from Names to TyThings
1668 * *
1669 ************************************************************************
1670 -}
1671
1672 tcIfaceGlobal :: Name -> IfL TyThing
1673 tcIfaceGlobal name
1674 | Just thing <- wiredInNameTyThing_maybe name
1675 -- Wired-in things include TyCons, DataCons, and Ids
1676 -- Even though we are in an interface file, we want to make
1677 -- sure the instances and RULES of this thing (particularly TyCon) are loaded
1678 -- Imagine: f :: Double -> Double
1679 = do { ifCheckWiredInThing thing; return thing }
1680
1681 | otherwise
1682 = do { env <- getGblEnv
1683 ; case if_rec_types env of { -- Note [Tying the knot]
1684 Just (mod, get_type_env)
1685 | nameIsLocalOrFrom mod name
1686 -> do -- It's defined in the module being compiled
1687 { type_env <- setLclEnv () get_type_env -- yuk
1688 ; case lookupNameEnv type_env name of
1689 Just thing -> return thing
1690 Nothing ->
1691 pprPanic "tcIfaceGlobal (local): not found"
1692 (ifKnotErr name (if_doc env) type_env)
1693 }
1694
1695 ; _ -> do
1696
1697 { hsc_env <- getTopEnv
1698 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1699 ; case mb_thing of {
1700 Just thing -> return thing ;
1701 Nothing -> do
1702
1703 { mb_thing <- importDecl name -- It's imported; go get it
1704 ; case mb_thing of
1705 Failed err -> failIfM err
1706 Succeeded thing -> return thing
1707 }}}}}
1708
1709 ifKnotErr :: Name -> SDoc -> TypeEnv -> SDoc
1710 ifKnotErr name env_doc type_env = vcat
1711 [ text "You are in a maze of twisty little passages, all alike."
1712 , text "While forcing the thunk for TyThing" <+> ppr name
1713 , text "which was lazily initialized by" <+> env_doc <> text ","
1714 , text "I tried to tie the knot, but I couldn't find" <+> ppr name
1715 , text "in the current type environment."
1716 , text "If you are developing GHC, please read Note [Tying the knot]"
1717 , text "and Note [Type-checking inside the knot]."
1718 , text "Consider rebuilding GHC with profiling for a better stack trace."
1719 , hang (text "Contents of current type environment:")
1720 2 (ppr type_env)
1721 ]
1722
1723 -- Note [Tying the knot]
1724 -- ~~~~~~~~~~~~~~~~~~~~~
1725 -- The if_rec_types field is used when we are compiling M.hs, which indirectly
1726 -- imports Foo.hi, which mentions M.T Then we look up M.T in M's type
1727 -- environment, which is splatted into if_rec_types after we've built M's type
1728 -- envt.
1729 --
1730 -- This is a dark and complicated part of GHC type checking, with a lot
1731 -- of moving parts. Interested readers should also look at:
1732 --
1733 -- * Note [Knot-tying typecheckIface]
1734 -- * Note [DFun knot-tying]
1735 -- * Note [hsc_type_env_var hack]
1736 --
1737 -- There is also a wiki page on the subject, see:
1738 --
1739 -- https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TyingTheKnot
1740
1741 tcIfaceTyConByName :: IfExtName -> IfL TyCon
1742 tcIfaceTyConByName name
1743 = do { thing <- tcIfaceGlobal name
1744 ; return (tyThingTyCon thing) }
1745
1746 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1747 tcIfaceTyCon (IfaceTyCon name info)
1748 = do { thing <- tcIfaceGlobal name
1749 ; return $ case ifaceTyConIsPromoted info of
1750 IsNotPromoted -> tyThingTyCon thing
1751 IsPromoted -> promoteDataCon $ tyThingDataCon thing }
1752
1753 tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
1754 tcIfaceCoAxiom name = do { thing <- tcIfaceImplicit name
1755 ; return (tyThingCoAxiom thing) }
1756
1757 tcIfaceDataCon :: Name -> IfL DataCon
1758 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1759 ; case thing of
1760 AConLike (RealDataCon dc) -> return dc
1761 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1762
1763 tcIfaceConLike :: Name -> IfL ConLike
1764 tcIfaceConLike name =
1765 do { thing <- tcIfaceGlobal name
1766 ; case thing of
1767 AConLike cl -> return cl
1768 _ -> pprPanic "tcIfaceExtCL" (ppr name$$ ppr thing) }
1769
1770
1771 tcIfaceExtId :: Name -> IfL Id
1772 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1773 ; case thing of
1774 AnId id -> return id
1775 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1776
1777 -- See Note [Resolving never-exported Names in TcIface]
1778 tcIfaceImplicit :: Name -> IfL TyThing
1779 tcIfaceImplicit n = do
1780 lcl_env <- getLclEnv
1781 case if_implicits_env lcl_env of
1782 Nothing -> tcIfaceGlobal n
1783 Just tenv ->
1784 case lookupTypeEnv tenv n of
1785 Nothing -> pprPanic "tcIfaceInst" (ppr n $$ ppr tenv)
1786 Just tything -> return tything
1787
1788 {-
1789 ************************************************************************
1790 * *
1791 Bindings
1792 * *
1793 ************************************************************************
1794 -}
1795
1796 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
1797 bindIfaceId (fs, ty) thing_inside
1798 = do { name <- newIfaceName (mkVarOccFS fs)
1799 ; ty' <- tcIfaceType ty
1800 ; let id = mkLocalIdOrCoVar name ty'
1801 ; extendIfaceIdEnv [id] (thing_inside id) }
1802
1803 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
1804 bindIfaceIds [] thing_inside = thing_inside []
1805 bindIfaceIds (b:bs) thing_inside
1806 = bindIfaceId b $ \b' ->
1807 bindIfaceIds bs $ \bs' ->
1808 thing_inside (b':bs')
1809
1810 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1811 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
1812 = bindIfaceId bndr thing_inside
1813 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1814 = bindIfaceTyVar bndr thing_inside
1815
1816 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1817 bindIfaceBndrs [] thing_inside = thing_inside []
1818 bindIfaceBndrs (b:bs) thing_inside
1819 = bindIfaceBndr b $ \ b' ->
1820 bindIfaceBndrs bs $ \ bs' ->
1821 thing_inside (b':bs')
1822
1823 -----------------------
1824 bindIfaceForAllBndrs :: [IfaceForAllBndr] -> ([TyVarBinder] -> IfL a) -> IfL a
1825 bindIfaceForAllBndrs [] thing_inside = thing_inside []
1826 bindIfaceForAllBndrs (bndr:bndrs) thing_inside
1827 = bindIfaceForAllBndr bndr $ \tv vis ->
1828 bindIfaceForAllBndrs bndrs $ \bndrs' ->
1829 thing_inside (mkTyVarBinder vis tv : bndrs')
1830
1831 bindIfaceForAllBndr :: IfaceForAllBndr -> (TyVar -> ArgFlag -> IfL a) -> IfL a
1832 bindIfaceForAllBndr (TvBndr tv vis) thing_inside
1833 = bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
1834
1835 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1836 bindIfaceTyVar (occ,kind) thing_inside
1837 = do { name <- newIfaceName (mkTyVarOccFS occ)
1838 ; tyvar <- mk_iface_tyvar name kind
1839 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1840
1841 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1842 mk_iface_tyvar name ifKind
1843 = do { kind <- tcIfaceType ifKind
1844 ; return (Var.mkTyVar name kind) }
1845
1846 bindIfaceTyConBinders :: [IfaceTyConBinder]
1847 -> ([TyConBinder] -> IfL a) -> IfL a
1848 bindIfaceTyConBinders [] thing_inside = thing_inside []
1849 bindIfaceTyConBinders (b:bs) thing_inside
1850 = bindIfaceTyConBinderX bindIfaceTyVar b $ \ b' ->
1851 bindIfaceTyConBinders bs $ \ bs' ->
1852 thing_inside (b':bs')
1853
1854 bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
1855 -> ([TyConBinder] -> IfL a) -> IfL a
1856 -- Used for type variable in nested associated data/type declarations
1857 -- where some of the type variables are already in scope
1858 -- class C a where { data T a b }
1859 -- Here 'a' is in scope when we look at the 'data T'
1860 bindIfaceTyConBinders_AT [] thing_inside
1861 = thing_inside []
1862 bindIfaceTyConBinders_AT (b : bs) thing_inside
1863 = bindIfaceTyConBinderX bind_tv b $ \b' ->
1864 bindIfaceTyConBinders_AT bs $ \bs' ->
1865 thing_inside (b':bs')
1866 where
1867 bind_tv tv thing
1868 = do { mb_tv <- lookupIfaceTyVar tv
1869 ; case mb_tv of
1870 Just b' -> thing b'
1871 Nothing -> bindIfaceTyVar tv thing }
1872
1873 bindIfaceTyConBinderX :: (IfaceTvBndr -> (TyVar -> IfL a) -> IfL a)
1874 -> IfaceTyConBinder
1875 -> (TyConBinder -> IfL a) -> IfL a
1876 bindIfaceTyConBinderX bind_tv (TvBndr tv vis) thing_inside
1877 = bind_tv tv $ \tv' ->
1878 thing_inside (TvBndr tv' vis)