Read COMPLETE sets from external packages
[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, tcIfaceCompleteSigs,
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 (IfaceCompleteMatch ms t) = return (CompleteMatch ms t)
1100
1101 {-
1102 ************************************************************************
1103 * *
1104 Vectorisation information
1105 * *
1106 ************************************************************************
1107 -}
1108
1109 -- We need access to the type environment as we need to look up information about type constructors
1110 -- (i.e., their data constructors and whether they are class type constructors). If a vectorised
1111 -- type constructor or class is defined in the same module as where it is vectorised, we cannot
1112 -- look that information up from the type constructor that we obtained via a 'forkM'ed
1113 -- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
1114 -- and again and again...
1115 --
1116 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
1117 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
1118 { ifaceVectInfoVar = vars
1119 , ifaceVectInfoTyCon = tycons
1120 , ifaceVectInfoTyConReuse = tyconsReuse
1121 , ifaceVectInfoParallelVars = parallelVars
1122 , ifaceVectInfoParallelTyCons = parallelTyCons
1123 })
1124 = do { let parallelTyConsSet = mkNameSet parallelTyCons
1125 ; vVars <- mapM vectVarMapping vars
1126 ; let varsSet = mkVarSet (map fst vVars)
1127 ; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
1128 ; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
1129 ; vParallelVars <- mapM vectVar parallelVars
1130 ; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
1131 ; return $ VectInfo
1132 { vectInfoVar = mkDVarEnv vVars `extendDVarEnvList` concat vScSels
1133 , vectInfoTyCon = mkNameEnv vTyCons
1134 , vectInfoDataCon = mkNameEnv (concat vDataCons)
1135 , vectInfoParallelVars = mkDVarSet vParallelVars
1136 , vectInfoParallelTyCons = parallelTyConsSet
1137 }
1138 }
1139 where
1140 vectVarMapping name
1141 = do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectOcc name)
1142 ; var <- forkM (text "vect var" <+> ppr name) $
1143 tcIfaceExtId name
1144 ; vVar <- forkM (text "vect vVar [mod =" <+>
1145 ppr mod <> text "; nameModule =" <+>
1146 ppr (nameModule name) <> text "]" <+> ppr vName) $
1147 tcIfaceExtId vName
1148 ; return (var, (var, vVar))
1149 }
1150 -- where
1151 -- lookupLocalOrExternalId name
1152 -- = do { let mb_id = lookupTypeEnv typeEnv name
1153 -- ; case mb_id of
1154 -- -- id is local
1155 -- Just (AnId id) -> return id
1156 -- -- name is not an Id => internal inconsistency
1157 -- Just _ -> notAnIdErr
1158 -- -- Id is external
1159 -- Nothing -> tcIfaceExtId name
1160 -- }
1161 --
1162 -- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
1163
1164 vectVar name
1165 = forkM (text "vect scalar var" <+> ppr name) $
1166 tcIfaceExtId name
1167
1168 vectTyConVectMapping vars name
1169 = do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectTyConOcc name)
1170 ; vectTyConMapping vars name vName
1171 }
1172
1173 vectTyConReuseMapping vars name
1174 = vectTyConMapping vars name name
1175
1176 vectTyConMapping vars name vName
1177 = do { tycon <- lookupLocalOrExternalTyCon name
1178 ; vTycon <- forkM (text "vTycon of" <+> ppr vName) $
1179 lookupLocalOrExternalTyCon vName
1180
1181 -- Map the data constructors of the original type constructor to those of the
1182 -- vectorised type constructor /unless/ the type constructor was vectorised
1183 -- abstractly; if it was vectorised abstractly, the workers of its data constructors
1184 -- do not appear in the set of vectorised variables.
1185 --
1186 -- NB: This is lazy! We don't pull at the type constructors before we actually use
1187 -- the data constructor mapping.
1188 ; let isAbstract | isClassTyCon tycon = False
1189 | datacon:_ <- tyConDataCons tycon
1190 = not $ dataConWrapId datacon `elemVarSet` vars
1191 | otherwise = True
1192 vDataCons | isAbstract = []
1193 | otherwise = [ (dataConName datacon, (datacon, vDatacon))
1194 | (datacon, vDatacon) <- zip (tyConDataCons tycon)
1195 (tyConDataCons vTycon)
1196 ]
1197
1198 -- Map the (implicit) superclass and methods selectors as they don't occur in
1199 -- the var map.
1200 vScSels | Just cls <- tyConClass_maybe tycon
1201 , Just vCls <- tyConClass_maybe vTycon
1202 = [ (sel, (sel, vSel))
1203 | (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
1204 ]
1205 | otherwise
1206 = []
1207
1208 ; return ( (name, (tycon, vTycon)) -- (T, T_v)
1209 , vDataCons -- list of (Ci, Ci_v)
1210 , vScSels -- list of (seli, seli_v)
1211 )
1212 }
1213 where
1214 -- we need a fully defined version of the type constructor to be able to extract
1215 -- its data constructors etc.
1216 lookupLocalOrExternalTyCon name
1217 = do { let mb_tycon = lookupTypeEnv typeEnv name
1218 ; case mb_tycon of
1219 -- tycon is local
1220 Just (ATyCon tycon) -> return tycon
1221 -- name is not a tycon => internal inconsistency
1222 Just _ -> notATyConErr
1223 -- tycon is external
1224 Nothing -> tcIfaceTyConByName name
1225 }
1226
1227 notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
1228
1229 {-
1230 ************************************************************************
1231 * *
1232 Types
1233 * *
1234 ************************************************************************
1235 -}
1236
1237 tcIfaceType :: IfaceType -> IfL Type
1238 tcIfaceType = go
1239 where
1240 go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
1241 go (IfaceFreeTyVar n) = pprPanic "tcIfaceType:IfaceFreeTyVar" (ppr n)
1242 go (IfaceAppTy t1 t2) = AppTy <$> go t1 <*> go t2
1243 go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
1244 go (IfaceFunTy t1 t2) = FunTy <$> go t1 <*> go t2
1245 go (IfaceDFunTy t1 t2) = FunTy <$> go t1 <*> go t2
1246 go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
1247 go (IfaceTyConApp tc tks)
1248 = do { tc' <- tcIfaceTyCon tc
1249 ; tks' <- mapM go (tcArgsIfaceTypes tks)
1250 ; return (mkTyConApp tc' tks') }
1251 go (IfaceForAllTy bndr t)
1252 = bindIfaceForAllBndr bndr $ \ tv' vis ->
1253 ForAllTy (TvBndr tv' vis) <$> go t
1254 go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
1255 go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
1256
1257 tcIfaceTupleTy :: TupleSort -> IsPromoted -> IfaceTcArgs -> IfL Type
1258 tcIfaceTupleTy sort is_promoted args
1259 = do { args' <- tcIfaceTcArgs args
1260 ; let arity = length args'
1261 ; base_tc <- tcTupleTyCon True sort arity
1262 ; case is_promoted of
1263 IsNotPromoted
1264 -> return (mkTyConApp base_tc args')
1265
1266 IsPromoted
1267 -> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
1268 kind_args = map typeKind args'
1269 ; return (mkTyConApp tc (kind_args ++ args')) } }
1270
1271 -- See Note [Unboxed tuple RuntimeRep vars] in TyCon
1272 tcTupleTyCon :: Bool -- True <=> typechecking a *type* (vs. an expr)
1273 -> TupleSort
1274 -> Arity -- the number of args. *not* the tuple arity.
1275 -> IfL TyCon
1276 tcTupleTyCon in_type sort arity
1277 = case sort of
1278 ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
1279 ; return (tyThingTyCon thing) }
1280 BoxedTuple -> return (tupleTyCon Boxed arity)
1281 UnboxedTuple -> return (tupleTyCon Unboxed arity')
1282 where arity' | in_type = arity `div` 2
1283 | otherwise = arity
1284 -- in expressions, we only have term args
1285
1286 tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
1287 tcIfaceTcArgs = mapM tcIfaceType . tcArgsIfaceTypes
1288
1289 -----------------------------------------
1290 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
1291 tcIfaceCtxt sts = mapM tcIfaceType sts
1292
1293 -----------------------------------------
1294 tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
1295 tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
1296 tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
1297
1298 {-
1299 %************************************************************************
1300 %* *
1301 Coercions
1302 * *
1303 ************************************************************************
1304 -}
1305
1306 tcIfaceCo :: IfaceCoercion -> IfL Coercion
1307 tcIfaceCo = go
1308 where
1309 go (IfaceReflCo r t) = Refl r <$> tcIfaceType t
1310 go (IfaceFunCo r c1 c2) = mkFunCo r <$> go c1 <*> go c2
1311 go (IfaceTyConAppCo r tc cs)
1312 = TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
1313 go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
1314 go (IfaceForAllCo tv k c) = do { k' <- go k
1315 ; bindIfaceTyVar tv $ \ tv' ->
1316 ForAllCo tv' k' <$> go c }
1317 go (IfaceCoVarCo n) = CoVarCo <$> go_var n
1318 go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
1319 go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
1320 <*> tcIfaceType t1 <*> tcIfaceType t2
1321 go (IfaceSymCo c) = SymCo <$> go c
1322 go (IfaceTransCo c1 c2) = TransCo <$> go c1
1323 <*> go c2
1324 go (IfaceInstCo c1 t2) = InstCo <$> go c1
1325 <*> go t2
1326 go (IfaceNthCo d c) = NthCo d <$> go c
1327 go (IfaceLRCo lr c) = LRCo lr <$> go c
1328 go (IfaceCoherenceCo c1 c2) = CoherenceCo <$> go c1
1329 <*> go c2
1330 go (IfaceKindCo c) = KindCo <$> go c
1331 go (IfaceSubCo c) = SubCo <$> go c
1332 go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> go_axiom_rule ax
1333 <*> mapM go cos
1334
1335 go_var :: FastString -> IfL CoVar
1336 go_var = tcIfaceLclId
1337
1338 go_axiom_rule :: FastString -> IfL CoAxiomRule
1339 go_axiom_rule n =
1340 case Map.lookup n typeNatCoAxiomRules of
1341 Just ax -> return ax
1342 _ -> pprPanic "go_axiom_rule" (ppr n)
1343
1344 tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
1345 tcIfaceUnivCoProv IfaceUnsafeCoerceProv = return UnsafeCoerceProv
1346 tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
1347 tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
1348 tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
1349 tcIfaceUnivCoProv (IfaceHoleProv _) =
1350 pprPanic "tcIfaceUnivCoProv" (text "holes can't occur in interface files")
1351
1352 {-
1353 ************************************************************************
1354 * *
1355 Core
1356 * *
1357 ************************************************************************
1358 -}
1359
1360 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
1361 tcIfaceExpr (IfaceType ty)
1362 = Type <$> tcIfaceType ty
1363
1364 tcIfaceExpr (IfaceCo co)
1365 = Coercion <$> tcIfaceCo co
1366
1367 tcIfaceExpr (IfaceCast expr co)
1368 = Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
1369
1370 tcIfaceExpr (IfaceLcl name)
1371 = Var <$> tcIfaceLclId name
1372
1373 tcIfaceExpr (IfaceExt gbl)
1374 = Var <$> tcIfaceExtId gbl
1375
1376 tcIfaceExpr (IfaceLit lit)
1377 = do lit' <- tcIfaceLit lit
1378 return (Lit lit')
1379
1380 tcIfaceExpr (IfaceFCall cc ty) = do
1381 ty' <- tcIfaceType ty
1382 u <- newUnique
1383 dflags <- getDynFlags
1384 return (Var (mkFCallId dflags u cc ty'))
1385
1386 tcIfaceExpr (IfaceTuple sort args)
1387 = do { args' <- mapM tcIfaceExpr args
1388 ; tc <- tcTupleTyCon False sort arity
1389 ; let con_tys = map exprType args'
1390 some_con_args = map Type con_tys ++ args'
1391 con_args = case sort of
1392 UnboxedTuple -> map (Type . getRuntimeRep "tcIfaceExpr") con_tys ++ some_con_args
1393 _ -> some_con_args
1394 -- Put the missing type arguments back in
1395 con_id = dataConWorkId (tyConSingleDataCon tc)
1396 ; return (mkApps (Var con_id) con_args) }
1397 where
1398 arity = length args
1399
1400 tcIfaceExpr (IfaceLam (bndr, os) body)
1401 = bindIfaceBndr bndr $ \bndr' ->
1402 Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
1403 where
1404 tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
1405 tcIfaceOneShot _ b = b
1406
1407 tcIfaceExpr (IfaceApp fun arg)
1408 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
1409
1410 tcIfaceExpr (IfaceECase scrut ty)
1411 = do { scrut' <- tcIfaceExpr scrut
1412 ; ty' <- tcIfaceType ty
1413 ; return (castBottomExpr scrut' ty') }
1414
1415 tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
1416 scrut' <- tcIfaceExpr scrut
1417 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
1418 let
1419 scrut_ty = exprType scrut'
1420 case_bndr' = mkLocalIdOrCoVar case_bndr_name scrut_ty
1421 tc_app = splitTyConApp scrut_ty
1422 -- NB: Won't always succeed (polymorphic case)
1423 -- but won't be demanded in those cases
1424 -- NB: not tcSplitTyConApp; we are looking at Core here
1425 -- look through non-rec newtypes to find the tycon that
1426 -- corresponds to the datacon in this case alternative
1427
1428 extendIfaceIdEnv [case_bndr'] $ do
1429 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
1430 return (Case scrut' case_bndr' (coreAltsType alts') alts')
1431
1432 tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info ji) rhs) body)
1433 = do { name <- newIfaceName (mkVarOccFS fs)
1434 ; ty' <- tcIfaceType ty
1435 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1436 name ty' info
1437 ; let id = mkLocalIdOrCoVarWithInfo name ty' id_info
1438 `asJoinId_maybe` tcJoinInfo ji
1439 ; rhs' <- tcIfaceExpr rhs
1440 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
1441 ; return (Let (NonRec id rhs') body') }
1442
1443 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
1444 = do { ids <- mapM tc_rec_bndr (map fst pairs)
1445 ; extendIfaceIdEnv ids $ do
1446 { pairs' <- zipWithM tc_pair pairs ids
1447 ; body' <- tcIfaceExpr body
1448 ; return (Let (Rec pairs') body') } }
1449 where
1450 tc_rec_bndr (IfLetBndr fs ty _ ji)
1451 = do { name <- newIfaceName (mkVarOccFS fs)
1452 ; ty' <- tcIfaceType ty
1453 ; return (mkLocalIdOrCoVar name ty' `asJoinId_maybe` tcJoinInfo ji) }
1454 tc_pair (IfLetBndr _ _ info _, rhs) id
1455 = do { rhs' <- tcIfaceExpr rhs
1456 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1457 (idName id) (idType id) info
1458 ; return (setIdInfo id id_info, rhs') }
1459
1460 tcIfaceExpr (IfaceTick tickish expr) = do
1461 expr' <- tcIfaceExpr expr
1462 -- If debug flag is not set: Ignore source notes
1463 dbgLvl <- fmap debugLevel getDynFlags
1464 case tickish of
1465 IfaceSource{} | dbgLvl > 0
1466 -> return expr'
1467 _otherwise -> do
1468 tickish' <- tcIfaceTickish tickish
1469 return (Tick tickish' expr')
1470
1471 -------------------------
1472 tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
1473 tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
1474 tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
1475 tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
1476
1477 -------------------------
1478 tcIfaceLit :: Literal -> IfL Literal
1479 -- Integer literals deserialise to (LitInteger i <error thunk>)
1480 -- so tcIfaceLit just fills in the type.
1481 -- See Note [Integer literals] in Literal
1482 tcIfaceLit (LitInteger i _)
1483 = do t <- tcIfaceTyConByName integerTyConName
1484 return (mkLitInteger i (mkTyConTy t))
1485 tcIfaceLit lit = return lit
1486
1487 -------------------------
1488 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
1489 -> (IfaceConAlt, [FastString], IfaceExpr)
1490 -> IfL (AltCon, [TyVar], CoreExpr)
1491 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
1492 = ASSERT( null names ) do
1493 rhs' <- tcIfaceExpr rhs
1494 return (DEFAULT, [], rhs')
1495
1496 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
1497 = ASSERT( null names ) do
1498 lit' <- tcIfaceLit lit
1499 rhs' <- tcIfaceExpr rhs
1500 return (LitAlt lit', [], rhs')
1501
1502 -- A case alternative is made quite a bit more complicated
1503 -- by the fact that we omit type annotations because we can
1504 -- work them out. True enough, but its not that easy!
1505 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
1506 = do { con <- tcIfaceDataCon data_occ
1507 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
1508 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
1509 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
1510
1511 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
1512 -> IfL (AltCon, [TyVar], CoreExpr)
1513 tcIfaceDataAlt con inst_tys arg_strs rhs
1514 = do { us <- newUniqueSupply
1515 ; let uniqs = uniqsFromSupply us
1516 ; let (ex_tvs, arg_ids)
1517 = dataConRepFSInstPat arg_strs uniqs con inst_tys
1518
1519 ; rhs' <- extendIfaceEnvs ex_tvs $
1520 extendIfaceIdEnv arg_ids $
1521 tcIfaceExpr rhs
1522 ; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
1523
1524 {-
1525 ************************************************************************
1526 * *
1527 IdInfo
1528 * *
1529 ************************************************************************
1530 -}
1531
1532 tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
1533 tcIdDetails _ IfVanillaId = return VanillaId
1534 tcIdDetails ty IfDFunId
1535 = return (DFunId (isNewTyCon (classTyCon cls)))
1536 where
1537 (_, _, cls, _) = tcSplitDFunTy ty
1538
1539 tcIdDetails _ (IfRecSelId tc naughty)
1540 = do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
1541 (fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
1542 tc
1543 ; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
1544 where
1545 tyThingPatSyn (AConLike (PatSynCon ps)) = ps
1546 tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
1547
1548 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
1549 tcIdInfo ignore_prags name ty info = do
1550 lcl_env <- getLclEnv
1551 -- Set the CgInfo to something sensible but uninformative before
1552 -- we start; default assumption is that it has CAFs
1553 let init_info | if_boot lcl_env = vanillaIdInfo `setUnfoldingInfo` BootUnfolding
1554 | otherwise = vanillaIdInfo
1555 if ignore_prags
1556 then return init_info
1557 else case info of
1558 NoInfo -> return init_info
1559 HasInfo info -> foldlM tcPrag init_info info
1560 where
1561 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
1562 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
1563 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
1564 tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
1565 tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
1566 tcPrag info HsLevity = return (info `setNeverLevPoly` ty)
1567
1568 -- The next two are lazy, so they don't transitively suck stuff in
1569 tcPrag info (HsUnfold lb if_unf)
1570 = do { unf <- tcUnfolding name ty info if_unf
1571 ; let info1 | lb = info `setOccInfo` strongLoopBreaker
1572 | otherwise = info
1573 ; return (info1 `setUnfoldingInfo` unf) }
1574
1575 tcJoinInfo :: IfaceJoinInfo -> Maybe JoinArity
1576 tcJoinInfo (IfaceJoinPoint ar) = Just ar
1577 tcJoinInfo IfaceNotJoinPoint = Nothing
1578
1579 tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
1580 tcUnfolding name _ info (IfCoreUnfold stable if_expr)
1581 = do { dflags <- getDynFlags
1582 ; mb_expr <- tcPragExpr name if_expr
1583 ; let unf_src | stable = InlineStable
1584 | otherwise = InlineRhs
1585 ; return $ case mb_expr of
1586 Nothing -> NoUnfolding
1587 Just expr -> mkUnfolding dflags unf_src
1588 True {- Top level -}
1589 (isBottomingSig strict_sig)
1590 expr
1591 }
1592 where
1593 -- Strictness should occur before unfolding!
1594 strict_sig = strictnessInfo info
1595 tcUnfolding name _ _ (IfCompulsory if_expr)
1596 = do { mb_expr <- tcPragExpr name if_expr
1597 ; return (case mb_expr of
1598 Nothing -> NoUnfolding
1599 Just expr -> mkCompulsoryUnfolding expr) }
1600
1601 tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
1602 = do { mb_expr <- tcPragExpr name if_expr
1603 ; return (case mb_expr of
1604 Nothing -> NoUnfolding
1605 Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
1606 where
1607 guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
1608
1609 tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
1610 = bindIfaceBndrs bs $ \ bs' ->
1611 do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
1612 ; return (case mb_ops1 of
1613 Nothing -> noUnfolding
1614 Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
1615 where
1616 doc = text "Class ops for dfun" <+> ppr name
1617 (_, _, cls, _) = tcSplitDFunTy dfun_ty
1618
1619 {-
1620 For unfoldings we try to do the job lazily, so that we never type check
1621 an unfolding that isn't going to be looked at.
1622 -}
1623
1624 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
1625 tcPragExpr name expr
1626 = forkM_maybe doc $ do
1627 core_expr' <- tcIfaceExpr expr
1628
1629 -- Check for type consistency in the unfolding
1630 whenGOptM Opt_DoCoreLinting $ do
1631 in_scope <- get_in_scope
1632 dflags <- getDynFlags
1633 case lintUnfolding dflags noSrcLoc in_scope core_expr' of
1634 Nothing -> return ()
1635 Just fail_msg -> do { mod <- getIfModule
1636 ; pprPanic "Iface Lint failure"
1637 (vcat [ text "In interface for" <+> ppr mod
1638 , hang doc 2 fail_msg
1639 , ppr name <+> equals <+> ppr core_expr'
1640 , text "Iface expr =" <+> ppr expr ]) }
1641 return core_expr'
1642 where
1643 doc = text "Unfolding of" <+> ppr name
1644
1645 get_in_scope :: IfL VarSet -- Totally disgusting; but just for linting
1646 get_in_scope
1647 = do { (gbl_env, lcl_env) <- getEnvs
1648 ; rec_ids <- case if_rec_types gbl_env of
1649 Nothing -> return []
1650 Just (_, get_env) -> do
1651 { type_env <- setLclEnv () get_env
1652 ; return (typeEnvIds type_env) }
1653 ; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
1654 bindingsVars (if_id_env lcl_env) `unionVarSet`
1655 mkVarSet rec_ids) }
1656
1657 bindingsVars :: FastStringEnv Var -> VarSet
1658 bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
1659 -- It's OK to use nonDetEltsUFM here because we immediately forget
1660 -- the ordering by creating a set
1661
1662 {-
1663 ************************************************************************
1664 * *
1665 Getting from Names to TyThings
1666 * *
1667 ************************************************************************
1668 -}
1669
1670 tcIfaceGlobal :: Name -> IfL TyThing
1671 tcIfaceGlobal name
1672 | Just thing <- wiredInNameTyThing_maybe name
1673 -- Wired-in things include TyCons, DataCons, and Ids
1674 -- Even though we are in an interface file, we want to make
1675 -- sure the instances and RULES of this thing (particularly TyCon) are loaded
1676 -- Imagine: f :: Double -> Double
1677 = do { ifCheckWiredInThing thing; return thing }
1678
1679 | otherwise
1680 = do { env <- getGblEnv
1681 ; case if_rec_types env of { -- Note [Tying the knot]
1682 Just (mod, get_type_env)
1683 | nameIsLocalOrFrom mod name
1684 -> do -- It's defined in the module being compiled
1685 { type_env <- setLclEnv () get_type_env -- yuk
1686 ; case lookupNameEnv type_env name of
1687 Just thing -> return thing
1688 Nothing ->
1689 pprPanic "tcIfaceGlobal (local): not found"
1690 (ifKnotErr name (if_doc env) type_env)
1691 }
1692
1693 ; _ -> do
1694
1695 { hsc_env <- getTopEnv
1696 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1697 ; case mb_thing of {
1698 Just thing -> return thing ;
1699 Nothing -> do
1700
1701 { mb_thing <- importDecl name -- It's imported; go get it
1702 ; case mb_thing of
1703 Failed err -> failIfM err
1704 Succeeded thing -> return thing
1705 }}}}}
1706
1707 ifKnotErr :: Name -> SDoc -> TypeEnv -> SDoc
1708 ifKnotErr name env_doc type_env = vcat
1709 [ text "You are in a maze of twisty little passages, all alike."
1710 , text "While forcing the thunk for TyThing" <+> ppr name
1711 , text "which was lazily initialized by" <+> env_doc <> text ","
1712 , text "I tried to tie the knot, but I couldn't find" <+> ppr name
1713 , text "in the current type environment."
1714 , text "If you are developing GHC, please read Note [Tying the knot]"
1715 , text "and Note [Type-checking inside the knot]."
1716 , text "Consider rebuilding GHC with profiling for a better stack trace."
1717 , hang (text "Contents of current type environment:")
1718 2 (ppr type_env)
1719 ]
1720
1721 -- Note [Tying the knot]
1722 -- ~~~~~~~~~~~~~~~~~~~~~
1723 -- The if_rec_types field is used when we are compiling M.hs, which indirectly
1724 -- imports Foo.hi, which mentions M.T Then we look up M.T in M's type
1725 -- environment, which is splatted into if_rec_types after we've built M's type
1726 -- envt.
1727 --
1728 -- This is a dark and complicated part of GHC type checking, with a lot
1729 -- of moving parts. Interested readers should also look at:
1730 --
1731 -- * Note [Knot-tying typecheckIface]
1732 -- * Note [DFun knot-tying]
1733 -- * Note [hsc_type_env_var hack]
1734 --
1735 -- There is also a wiki page on the subject, see:
1736 --
1737 -- https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TyingTheKnot
1738
1739 tcIfaceTyConByName :: IfExtName -> IfL TyCon
1740 tcIfaceTyConByName name
1741 = do { thing <- tcIfaceGlobal name
1742 ; return (tyThingTyCon thing) }
1743
1744 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1745 tcIfaceTyCon (IfaceTyCon name info)
1746 = do { thing <- tcIfaceGlobal name
1747 ; return $ case ifaceTyConIsPromoted info of
1748 IsNotPromoted -> tyThingTyCon thing
1749 IsPromoted -> promoteDataCon $ tyThingDataCon thing }
1750
1751 tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
1752 tcIfaceCoAxiom name = do { thing <- tcIfaceImplicit name
1753 ; return (tyThingCoAxiom thing) }
1754
1755 tcIfaceDataCon :: Name -> IfL DataCon
1756 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1757 ; case thing of
1758 AConLike (RealDataCon dc) -> return dc
1759 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1760
1761 tcIfaceExtId :: Name -> IfL Id
1762 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1763 ; case thing of
1764 AnId id -> return id
1765 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1766
1767 -- See Note [Resolving never-exported Names in TcIface]
1768 tcIfaceImplicit :: Name -> IfL TyThing
1769 tcIfaceImplicit n = do
1770 lcl_env <- getLclEnv
1771 case if_implicits_env lcl_env of
1772 Nothing -> tcIfaceGlobal n
1773 Just tenv ->
1774 case lookupTypeEnv tenv n of
1775 Nothing -> pprPanic "tcIfaceInst" (ppr n $$ ppr tenv)
1776 Just tything -> return tything
1777
1778 {-
1779 ************************************************************************
1780 * *
1781 Bindings
1782 * *
1783 ************************************************************************
1784 -}
1785
1786 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
1787 bindIfaceId (fs, ty) thing_inside
1788 = do { name <- newIfaceName (mkVarOccFS fs)
1789 ; ty' <- tcIfaceType ty
1790 ; let id = mkLocalIdOrCoVar name ty'
1791 ; extendIfaceIdEnv [id] (thing_inside id) }
1792
1793 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
1794 bindIfaceIds [] thing_inside = thing_inside []
1795 bindIfaceIds (b:bs) thing_inside
1796 = bindIfaceId b $ \b' ->
1797 bindIfaceIds bs $ \bs' ->
1798 thing_inside (b':bs')
1799
1800 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1801 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
1802 = bindIfaceId bndr thing_inside
1803 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1804 = bindIfaceTyVar bndr thing_inside
1805
1806 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1807 bindIfaceBndrs [] thing_inside = thing_inside []
1808 bindIfaceBndrs (b:bs) thing_inside
1809 = bindIfaceBndr b $ \ b' ->
1810 bindIfaceBndrs bs $ \ bs' ->
1811 thing_inside (b':bs')
1812
1813 -----------------------
1814 bindIfaceForAllBndrs :: [IfaceForAllBndr] -> ([TyVarBinder] -> IfL a) -> IfL a
1815 bindIfaceForAllBndrs [] thing_inside = thing_inside []
1816 bindIfaceForAllBndrs (bndr:bndrs) thing_inside
1817 = bindIfaceForAllBndr bndr $ \tv vis ->
1818 bindIfaceForAllBndrs bndrs $ \bndrs' ->
1819 thing_inside (mkTyVarBinder vis tv : bndrs')
1820
1821 bindIfaceForAllBndr :: IfaceForAllBndr -> (TyVar -> ArgFlag -> IfL a) -> IfL a
1822 bindIfaceForAllBndr (TvBndr tv vis) thing_inside
1823 = bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
1824
1825 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1826 bindIfaceTyVar (occ,kind) thing_inside
1827 = do { name <- newIfaceName (mkTyVarOccFS occ)
1828 ; tyvar <- mk_iface_tyvar name kind
1829 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1830
1831 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1832 mk_iface_tyvar name ifKind
1833 = do { kind <- tcIfaceType ifKind
1834 ; return (Var.mkTyVar name kind) }
1835
1836 bindIfaceTyConBinders :: [IfaceTyConBinder]
1837 -> ([TyConBinder] -> IfL a) -> IfL a
1838 bindIfaceTyConBinders [] thing_inside = thing_inside []
1839 bindIfaceTyConBinders (b:bs) thing_inside
1840 = bindIfaceTyConBinderX bindIfaceTyVar b $ \ b' ->
1841 bindIfaceTyConBinders bs $ \ bs' ->
1842 thing_inside (b':bs')
1843
1844 bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
1845 -> ([TyConBinder] -> IfL a) -> IfL a
1846 -- Used for type variable in nested associated data/type declarations
1847 -- where some of the type variables are already in scope
1848 -- class C a where { data T a b }
1849 -- Here 'a' is in scope when we look at the 'data T'
1850 bindIfaceTyConBinders_AT [] thing_inside
1851 = thing_inside []
1852 bindIfaceTyConBinders_AT (b : bs) thing_inside
1853 = bindIfaceTyConBinderX bind_tv b $ \b' ->
1854 bindIfaceTyConBinders_AT bs $ \bs' ->
1855 thing_inside (b':bs')
1856 where
1857 bind_tv tv thing
1858 = do { mb_tv <- lookupIfaceTyVar tv
1859 ; case mb_tv of
1860 Just b' -> thing b'
1861 Nothing -> bindIfaceTyVar tv thing }
1862
1863 bindIfaceTyConBinderX :: (IfaceTvBndr -> (TyVar -> IfL a) -> IfL a)
1864 -> IfaceTyConBinder
1865 -> (TyConBinder -> IfL a) -> IfL a
1866 bindIfaceTyConBinderX bind_tv (TvBndr tv vis) thing_inside
1867 = bind_tv tv $ \tv' ->
1868 thing_inside (TvBndr tv' vis)