Preserve CoVar uniques during pretty printing
[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 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 -- Must be done lazily, because axioms are forced when checking
811 -- for family instance consistency, and the RHS may mention
812 -- a hs-boot declared type constructor that is going to be
813 -- defined by this module.
814 -- e.g. type instance F Int = ToBeDefined
815 -- See Trac #13803
816 ; tc_branches <- forkM (text "Axiom branches" <+> ppr tc_name)
817 $ tc_ax_branches branches
818 ; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
819 , co_ax_name = tc_name
820 , co_ax_tc = tc_tycon
821 , co_ax_role = role
822 , co_ax_branches = manyBranches tc_branches
823 , co_ax_implicit = False }
824 ; return (ACoAxiom axiom) }
825
826 tc_iface_decl _ _ (IfacePatSyn{ ifName = name
827 , ifPatMatcher = if_matcher
828 , ifPatBuilder = if_builder
829 , ifPatIsInfix = is_infix
830 , ifPatUnivBndrs = univ_bndrs
831 , ifPatExBndrs = ex_bndrs
832 , ifPatProvCtxt = prov_ctxt
833 , ifPatReqCtxt = req_ctxt
834 , ifPatArgs = args
835 , ifPatTy = pat_ty
836 , ifFieldLabels = field_labels })
837 = do { traceIf (text "tc_iface_decl" <+> ppr name)
838 ; matcher <- tc_pr if_matcher
839 ; builder <- fmapMaybeM tc_pr if_builder
840 ; bindIfaceForAllBndrs univ_bndrs $ \univ_tvs -> do
841 { bindIfaceForAllBndrs ex_bndrs $ \ex_tvs -> do
842 { patsyn <- forkM (mk_doc name) $
843 do { prov_theta <- tcIfaceCtxt prov_ctxt
844 ; req_theta <- tcIfaceCtxt req_ctxt
845 ; pat_ty <- tcIfaceType pat_ty
846 ; arg_tys <- mapM tcIfaceType args
847 ; return $ buildPatSyn name is_infix matcher builder
848 (univ_tvs, req_theta)
849 (ex_tvs, prov_theta)
850 arg_tys pat_ty field_labels }
851 ; return $ AConLike . PatSynCon $ patsyn }}}
852 where
853 mk_doc n = text "Pattern synonym" <+> ppr n
854 tc_pr :: (IfExtName, Bool) -> IfL (Id, Bool)
855 tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
856 ; return (id, b) }
857
858 tc_fd :: FunDep IfLclName -> IfL (FunDep TyVar)
859 tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
860 ; tvs2' <- mapM tcIfaceTyVar tvs2
861 ; return (tvs1', tvs2') }
862
863 tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
864 tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
865
866 tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
867 tc_ax_branch prev_branches
868 (IfaceAxBranch { ifaxbTyVars = tv_bndrs, ifaxbCoVars = cv_bndrs
869 , ifaxbLHS = lhs, ifaxbRHS = rhs
870 , ifaxbRoles = roles, ifaxbIncomps = incomps })
871 = bindIfaceTyConBinders_AT
872 (map (\b -> TvBndr b (NamedTCB Inferred)) tv_bndrs) $ \ tvs ->
873 -- The _AT variant is needed here; see Note [CoAxBranch type variables] in CoAxiom
874 bindIfaceIds cv_bndrs $ \ cvs -> do
875 { tc_lhs <- tcIfaceTcArgs lhs
876 ; tc_rhs <- tcIfaceType rhs
877 ; let br = CoAxBranch { cab_loc = noSrcSpan
878 , cab_tvs = binderVars tvs
879 , cab_cvs = cvs
880 , cab_lhs = tc_lhs
881 , cab_roles = roles
882 , cab_rhs = tc_rhs
883 , cab_incomps = map (prev_branches `getNth`) incomps }
884 ; return (prev_branches ++ [br]) }
885
886 tcIfaceDataCons :: Name -> TyCon -> [TyConBinder] -> IfaceConDecls -> IfL AlgTyConRhs
887 tcIfaceDataCons tycon_name tycon tc_tybinders if_cons
888 = case if_cons of
889 IfAbstractTyCon -> return AbstractTyCon
890 IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
891 ; return (mkDataTyConRhs data_cons) }
892 IfNewTyCon con -> do { data_con <- tc_con_decl con
893 ; mkNewTyConRhs tycon_name tycon data_con }
894 where
895 univ_tv_bndrs :: [TyVarBinder]
896 univ_tv_bndrs = tyConTyVarBinders tc_tybinders
897
898 tc_con_decl (IfCon { ifConInfix = is_infix,
899 ifConExTvs = ex_bndrs,
900 ifConName = dc_name,
901 ifConCtxt = ctxt, ifConEqSpec = spec,
902 ifConArgTys = args, ifConFields = lbl_names,
903 ifConStricts = if_stricts,
904 ifConSrcStricts = if_src_stricts})
905 = -- Universally-quantified tyvars are shared with
906 -- parent TyCon, and are already in scope
907 bindIfaceForAllBndrs ex_bndrs $ \ ex_tv_bndrs -> do
908 { traceIf (text "Start interface-file tc_con_decl" <+> ppr dc_name)
909
910 -- Read the context and argument types, but lazily for two reasons
911 -- (a) to avoid looking tugging on a recursive use of
912 -- the type itself, which is knot-tied
913 -- (b) to avoid faulting in the component types unless
914 -- they are really needed
915 ; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc dc_name) $
916 do { eq_spec <- tcIfaceEqSpec spec
917 ; theta <- tcIfaceCtxt ctxt
918 ; arg_tys <- mapM tcIfaceType args
919 ; stricts <- mapM tc_strict if_stricts
920 -- The IfBang field can mention
921 -- the type itself; hence inside forkM
922 ; return (eq_spec, theta, arg_tys, stricts) }
923
924 -- Remember, tycon is the representation tycon
925 ; let orig_res_ty = mkFamilyTyConApp tycon
926 (substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec))
927 (binderVars tc_tybinders))
928
929 ; prom_rep_name <- newTyConRepName dc_name
930
931 ; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr dc_name))
932 dc_name is_infix prom_rep_name
933 (map src_strict if_src_stricts)
934 (Just stricts)
935 -- Pass the HsImplBangs (i.e. final
936 -- decisions) to buildDataCon; it'll use
937 -- these to guide the construction of a
938 -- worker.
939 -- See Note [Bangs on imported data constructors] in MkId
940 lbl_names
941 univ_tv_bndrs ex_tv_bndrs
942 eq_spec theta
943 arg_tys orig_res_ty tycon
944 ; traceIf (text "Done interface-file tc_con_decl" <+> ppr dc_name)
945 ; return con }
946 mk_doc con_name = text "Constructor" <+> ppr con_name
947
948 tc_strict :: IfaceBang -> IfL HsImplBang
949 tc_strict IfNoBang = return (HsLazy)
950 tc_strict IfStrict = return (HsStrict)
951 tc_strict IfUnpack = return (HsUnpack Nothing)
952 tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
953 ; return (HsUnpack (Just co)) }
954
955 src_strict :: IfaceSrcBang -> HsSrcBang
956 src_strict (IfSrcBang unpk bang) = HsSrcBang NoSourceText unpk bang
957
958 tcIfaceEqSpec :: IfaceEqSpec -> IfL [EqSpec]
959 tcIfaceEqSpec spec
960 = mapM do_item spec
961 where
962 do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
963 ; ty <- tcIfaceType if_ty
964 ; return (mkEqSpec tv ty) }
965
966 {-
967 Note [Synonym kind loop]
968 ~~~~~~~~~~~~~~~~~~~~~~~~
969 Notice that we eagerly grab the *kind* from the interface file, but
970 build a forkM thunk for the *rhs* (and family stuff). To see why,
971 consider this (Trac #2412)
972
973 M.hs: module M where { import X; data T = MkT S }
974 X.hs: module X where { import {-# SOURCE #-} M; type S = T }
975 M.hs-boot: module M where { data T }
976
977 When kind-checking M.hs we need S's kind. But we do not want to
978 find S's kind from (typeKind S-rhs), because we don't want to look at
979 S-rhs yet! Since S is imported from X.hi, S gets just one chance to
980 be defined, and we must not do that until we've finished with M.T.
981
982 Solution: record S's kind in the interface file; now we can safely
983 look at it.
984
985 ************************************************************************
986 * *
987 Instances
988 * *
989 ************************************************************************
990 -}
991
992 tcIfaceInst :: IfaceClsInst -> IfL ClsInst
993 tcIfaceInst (IfaceClsInst { ifDFun = dfun_name, ifOFlag = oflag
994 , ifInstCls = cls, ifInstTys = mb_tcs
995 , ifInstOrph = orph })
996 = do { dfun <- forkM (text "Dict fun" <+> ppr dfun_name) $
997 fmap tyThingId (tcIfaceImplicit dfun_name)
998 ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
999 ; return (mkImportedInstance cls mb_tcs' dfun_name dfun oflag orph) }
1000
1001 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
1002 tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
1003 , ifFamInstAxiom = axiom_name } )
1004 = do { axiom' <- forkM (text "Axiom" <+> ppr axiom_name) $
1005 tcIfaceCoAxiom axiom_name
1006 -- will panic if branched, but that's OK
1007 ; let axiom'' = toUnbranchedAxiom axiom'
1008 mb_tcs' = map (fmap ifaceTyConName) mb_tcs
1009 ; return (mkImportedFamInst fam mb_tcs' axiom'') }
1010
1011 {-
1012 ************************************************************************
1013 * *
1014 Rules
1015 * *
1016 ************************************************************************
1017
1018 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
1019 are in the type environment. However, remember that typechecking a Rule may
1020 (as a side effect) augment the type envt, and so we may need to iterate the process.
1021 -}
1022
1023 tcIfaceRules :: Bool -- True <=> ignore rules
1024 -> [IfaceRule]
1025 -> IfL [CoreRule]
1026 tcIfaceRules ignore_prags if_rules
1027 | ignore_prags = return []
1028 | otherwise = mapM tcIfaceRule if_rules
1029
1030 tcIfaceRule :: IfaceRule -> IfL CoreRule
1031 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
1032 ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
1033 ifRuleAuto = auto, ifRuleOrph = orph })
1034 = do { ~(bndrs', args', rhs') <-
1035 -- Typecheck the payload lazily, in the hope it'll never be looked at
1036 forkM (text "Rule" <+> pprRuleName name) $
1037 bindIfaceBndrs bndrs $ \ bndrs' ->
1038 do { args' <- mapM tcIfaceExpr args
1039 ; rhs' <- tcIfaceExpr rhs
1040 ; return (bndrs', args', rhs') }
1041 ; let mb_tcs = map ifTopFreeName args
1042 ; this_mod <- getIfModule
1043 ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
1044 ru_bndrs = bndrs', ru_args = args',
1045 ru_rhs = occurAnalyseExpr rhs',
1046 ru_rough = mb_tcs,
1047 ru_origin = this_mod,
1048 ru_orphan = orph,
1049 ru_auto = auto,
1050 ru_local = False }) } -- An imported RULE is never for a local Id
1051 -- or, even if it is (module loop, perhaps)
1052 -- we'll just leave it in the non-local set
1053 where
1054 -- This function *must* mirror exactly what Rules.roughTopNames does
1055 -- We could have stored the ru_rough field in the iface file
1056 -- but that would be redundant, I think.
1057 -- The only wrinkle is that we must not be deceived by
1058 -- type synonyms at the top of a type arg. Since
1059 -- we can't tell at this point, we are careful not
1060 -- to write them out in coreRuleToIfaceRule
1061 ifTopFreeName :: IfaceExpr -> Maybe Name
1062 ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
1063 ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (tcArgsIfaceTypes ts)))
1064 ifTopFreeName (IfaceApp f _) = ifTopFreeName f
1065 ifTopFreeName (IfaceExt n) = Just n
1066 ifTopFreeName _ = Nothing
1067
1068 {-
1069 ************************************************************************
1070 * *
1071 Annotations
1072 * *
1073 ************************************************************************
1074 -}
1075
1076 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
1077 tcIfaceAnnotations = mapM tcIfaceAnnotation
1078
1079 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
1080 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
1081 target' <- tcIfaceAnnTarget target
1082 return $ Annotation {
1083 ann_target = target',
1084 ann_value = serialized
1085 }
1086
1087 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
1088 tcIfaceAnnTarget (NamedTarget occ) = do
1089 name <- lookupIfaceTop occ
1090 return $ NamedTarget name
1091 tcIfaceAnnTarget (ModuleTarget mod) = do
1092 return $ ModuleTarget mod
1093
1094 {-
1095 ************************************************************************
1096 * *
1097 Complete Match Pragmas
1098 * *
1099 ************************************************************************
1100 -}
1101
1102 tcIfaceCompleteSigs :: [IfaceCompleteMatch] -> IfL [CompleteMatch]
1103 tcIfaceCompleteSigs = mapM tcIfaceCompleteSig
1104
1105 tcIfaceCompleteSig :: IfaceCompleteMatch -> IfL CompleteMatch
1106 tcIfaceCompleteSig (IfaceCompleteMatch ms t) = return (CompleteMatch ms t)
1107
1108 {-
1109 ************************************************************************
1110 * *
1111 Vectorisation information
1112 * *
1113 ************************************************************************
1114 -}
1115
1116 -- We need access to the type environment as we need to look up information about type constructors
1117 -- (i.e., their data constructors and whether they are class type constructors). If a vectorised
1118 -- type constructor or class is defined in the same module as where it is vectorised, we cannot
1119 -- look that information up from the type constructor that we obtained via a 'forkM'ed
1120 -- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
1121 -- and again and again...
1122 --
1123 tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
1124 tcIfaceVectInfo mod typeEnv (IfaceVectInfo
1125 { ifaceVectInfoVar = vars
1126 , ifaceVectInfoTyCon = tycons
1127 , ifaceVectInfoTyConReuse = tyconsReuse
1128 , ifaceVectInfoParallelVars = parallelVars
1129 , ifaceVectInfoParallelTyCons = parallelTyCons
1130 })
1131 = do { let parallelTyConsSet = mkNameSet parallelTyCons
1132 ; vVars <- mapM vectVarMapping vars
1133 ; let varsSet = mkVarSet (map fst vVars)
1134 ; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
1135 ; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
1136 ; vParallelVars <- mapM vectVar parallelVars
1137 ; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
1138 ; return $ VectInfo
1139 { vectInfoVar = mkDVarEnv vVars `extendDVarEnvList` concat vScSels
1140 , vectInfoTyCon = mkNameEnv vTyCons
1141 , vectInfoDataCon = mkNameEnv (concat vDataCons)
1142 , vectInfoParallelVars = mkDVarSet vParallelVars
1143 , vectInfoParallelTyCons = parallelTyConsSet
1144 }
1145 }
1146 where
1147 vectVarMapping name
1148 = do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectOcc name)
1149 ; var <- forkM (text "vect var" <+> ppr name) $
1150 tcIfaceExtId name
1151 ; vVar <- forkM (text "vect vVar [mod =" <+>
1152 ppr mod <> text "; nameModule =" <+>
1153 ppr (nameModule name) <> text "]" <+> ppr vName) $
1154 tcIfaceExtId vName
1155 ; return (var, (var, vVar))
1156 }
1157 -- where
1158 -- lookupLocalOrExternalId name
1159 -- = do { let mb_id = lookupTypeEnv typeEnv name
1160 -- ; case mb_id of
1161 -- -- id is local
1162 -- Just (AnId id) -> return id
1163 -- -- name is not an Id => internal inconsistency
1164 -- Just _ -> notAnIdErr
1165 -- -- Id is external
1166 -- Nothing -> tcIfaceExtId name
1167 -- }
1168 --
1169 -- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
1170
1171 vectVar name
1172 = forkM (text "vect scalar var" <+> ppr name) $
1173 tcIfaceExtId name
1174
1175 vectTyConVectMapping vars name
1176 = do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectTyConOcc name)
1177 ; vectTyConMapping vars name vName
1178 }
1179
1180 vectTyConReuseMapping vars name
1181 = vectTyConMapping vars name name
1182
1183 vectTyConMapping vars name vName
1184 = do { tycon <- lookupLocalOrExternalTyCon name
1185 ; vTycon <- forkM (text "vTycon of" <+> ppr vName) $
1186 lookupLocalOrExternalTyCon vName
1187
1188 -- Map the data constructors of the original type constructor to those of the
1189 -- vectorised type constructor /unless/ the type constructor was vectorised
1190 -- abstractly; if it was vectorised abstractly, the workers of its data constructors
1191 -- do not appear in the set of vectorised variables.
1192 --
1193 -- NB: This is lazy! We don't pull at the type constructors before we actually use
1194 -- the data constructor mapping.
1195 ; let isAbstract | isClassTyCon tycon = False
1196 | datacon:_ <- tyConDataCons tycon
1197 = not $ dataConWrapId datacon `elemVarSet` vars
1198 | otherwise = True
1199 vDataCons | isAbstract = []
1200 | otherwise = [ (dataConName datacon, (datacon, vDatacon))
1201 | (datacon, vDatacon) <- zip (tyConDataCons tycon)
1202 (tyConDataCons vTycon)
1203 ]
1204
1205 -- Map the (implicit) superclass and methods selectors as they don't occur in
1206 -- the var map.
1207 vScSels | Just cls <- tyConClass_maybe tycon
1208 , Just vCls <- tyConClass_maybe vTycon
1209 = [ (sel, (sel, vSel))
1210 | (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
1211 ]
1212 | otherwise
1213 = []
1214
1215 ; return ( (name, (tycon, vTycon)) -- (T, T_v)
1216 , vDataCons -- list of (Ci, Ci_v)
1217 , vScSels -- list of (seli, seli_v)
1218 )
1219 }
1220 where
1221 -- we need a fully defined version of the type constructor to be able to extract
1222 -- its data constructors etc.
1223 lookupLocalOrExternalTyCon name
1224 = do { let mb_tycon = lookupTypeEnv typeEnv name
1225 ; case mb_tycon of
1226 -- tycon is local
1227 Just (ATyCon tycon) -> return tycon
1228 -- name is not a tycon => internal inconsistency
1229 Just _ -> notATyConErr
1230 -- tycon is external
1231 Nothing -> tcIfaceTyConByName name
1232 }
1233
1234 notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
1235
1236 {-
1237 ************************************************************************
1238 * *
1239 Types
1240 * *
1241 ************************************************************************
1242 -}
1243
1244 tcIfaceType :: IfaceType -> IfL Type
1245 tcIfaceType = go
1246 where
1247 go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
1248 go (IfaceFreeTyVar n) = pprPanic "tcIfaceType:IfaceFreeTyVar" (ppr n)
1249 go (IfaceAppTy t1 t2) = AppTy <$> go t1 <*> go t2
1250 go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
1251 go (IfaceFunTy t1 t2) = FunTy <$> go t1 <*> go t2
1252 go (IfaceDFunTy t1 t2) = FunTy <$> go t1 <*> go t2
1253 go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
1254 go (IfaceTyConApp tc tks)
1255 = do { tc' <- tcIfaceTyCon tc
1256 ; tks' <- mapM go (tcArgsIfaceTypes tks)
1257 ; return (mkTyConApp tc' tks') }
1258 go (IfaceForAllTy bndr t)
1259 = bindIfaceForAllBndr bndr $ \ tv' vis ->
1260 ForAllTy (TvBndr tv' vis) <$> go t
1261 go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
1262 go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
1263
1264 tcIfaceTupleTy :: TupleSort -> IsPromoted -> IfaceTcArgs -> IfL Type
1265 tcIfaceTupleTy sort is_promoted args
1266 = do { args' <- tcIfaceTcArgs args
1267 ; let arity = length args'
1268 ; base_tc <- tcTupleTyCon True sort arity
1269 ; case is_promoted of
1270 IsNotPromoted
1271 -> return (mkTyConApp base_tc args')
1272
1273 IsPromoted
1274 -> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
1275 kind_args = map typeKind args'
1276 ; return (mkTyConApp tc (kind_args ++ args')) } }
1277
1278 -- See Note [Unboxed tuple RuntimeRep vars] in TyCon
1279 tcTupleTyCon :: Bool -- True <=> typechecking a *type* (vs. an expr)
1280 -> TupleSort
1281 -> Arity -- the number of args. *not* the tuple arity.
1282 -> IfL TyCon
1283 tcTupleTyCon in_type sort arity
1284 = case sort of
1285 ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
1286 ; return (tyThingTyCon thing) }
1287 BoxedTuple -> return (tupleTyCon Boxed arity)
1288 UnboxedTuple -> return (tupleTyCon Unboxed arity')
1289 where arity' | in_type = arity `div` 2
1290 | otherwise = arity
1291 -- in expressions, we only have term args
1292
1293 tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
1294 tcIfaceTcArgs = mapM tcIfaceType . tcArgsIfaceTypes
1295
1296 -----------------------------------------
1297 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
1298 tcIfaceCtxt sts = mapM tcIfaceType sts
1299
1300 -----------------------------------------
1301 tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
1302 tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
1303 tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
1304
1305 {-
1306 %************************************************************************
1307 %* *
1308 Coercions
1309 * *
1310 ************************************************************************
1311 -}
1312
1313 tcIfaceCo :: IfaceCoercion -> IfL Coercion
1314 tcIfaceCo = go
1315 where
1316 go (IfaceReflCo r t) = Refl r <$> tcIfaceType t
1317 go (IfaceFunCo r c1 c2) = mkFunCo r <$> go c1 <*> go c2
1318 go (IfaceTyConAppCo r tc cs)
1319 = TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
1320 go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
1321 go (IfaceForAllCo tv k c) = do { k' <- go k
1322 ; bindIfaceTyVar tv $ \ tv' ->
1323 ForAllCo tv' k' <$> go c }
1324 go (IfaceFreeCoVar c) = pprPanic "tcIfaceCo:IfaceFreeCoVar" (ppr c)
1325 go (IfaceCoVarCo n) = CoVarCo <$> go_var n
1326 go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
1327 go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
1328 <*> tcIfaceType t1 <*> tcIfaceType t2
1329 go (IfaceSymCo c) = SymCo <$> go c
1330 go (IfaceTransCo c1 c2) = TransCo <$> go c1
1331 <*> go c2
1332 go (IfaceInstCo c1 t2) = InstCo <$> go c1
1333 <*> go t2
1334 go (IfaceNthCo d c) = NthCo d <$> go c
1335 go (IfaceLRCo lr c) = LRCo lr <$> go c
1336 go (IfaceCoherenceCo c1 c2) = CoherenceCo <$> go c1
1337 <*> go c2
1338 go (IfaceKindCo c) = KindCo <$> go c
1339 go (IfaceSubCo c) = SubCo <$> go c
1340 go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> go_axiom_rule ax
1341 <*> mapM go cos
1342
1343 go_var :: FastString -> IfL CoVar
1344 go_var = tcIfaceLclId
1345
1346 go_axiom_rule :: FastString -> IfL CoAxiomRule
1347 go_axiom_rule n =
1348 case Map.lookup n typeNatCoAxiomRules of
1349 Just ax -> return ax
1350 _ -> pprPanic "go_axiom_rule" (ppr n)
1351
1352 tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
1353 tcIfaceUnivCoProv IfaceUnsafeCoerceProv = return UnsafeCoerceProv
1354 tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
1355 tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
1356 tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
1357 tcIfaceUnivCoProv (IfaceHoleProv _) =
1358 pprPanic "tcIfaceUnivCoProv" (text "holes can't occur in interface files")
1359
1360 {-
1361 ************************************************************************
1362 * *
1363 Core
1364 * *
1365 ************************************************************************
1366 -}
1367
1368 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
1369 tcIfaceExpr (IfaceType ty)
1370 = Type <$> tcIfaceType ty
1371
1372 tcIfaceExpr (IfaceCo co)
1373 = Coercion <$> tcIfaceCo co
1374
1375 tcIfaceExpr (IfaceCast expr co)
1376 = Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
1377
1378 tcIfaceExpr (IfaceLcl name)
1379 = Var <$> tcIfaceLclId name
1380
1381 tcIfaceExpr (IfaceExt gbl)
1382 = Var <$> tcIfaceExtId gbl
1383
1384 tcIfaceExpr (IfaceLit lit)
1385 = do lit' <- tcIfaceLit lit
1386 return (Lit lit')
1387
1388 tcIfaceExpr (IfaceFCall cc ty) = do
1389 ty' <- tcIfaceType ty
1390 u <- newUnique
1391 dflags <- getDynFlags
1392 return (Var (mkFCallId dflags u cc ty'))
1393
1394 tcIfaceExpr (IfaceTuple sort args)
1395 = do { args' <- mapM tcIfaceExpr args
1396 ; tc <- tcTupleTyCon False sort arity
1397 ; let con_tys = map exprType args'
1398 some_con_args = map Type con_tys ++ args'
1399 con_args = case sort of
1400 UnboxedTuple -> map (Type . getRuntimeRep "tcIfaceExpr") con_tys ++ some_con_args
1401 _ -> some_con_args
1402 -- Put the missing type arguments back in
1403 con_id = dataConWorkId (tyConSingleDataCon tc)
1404 ; return (mkApps (Var con_id) con_args) }
1405 where
1406 arity = length args
1407
1408 tcIfaceExpr (IfaceLam (bndr, os) body)
1409 = bindIfaceBndr bndr $ \bndr' ->
1410 Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
1411 where
1412 tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
1413 tcIfaceOneShot _ b = b
1414
1415 tcIfaceExpr (IfaceApp fun arg)
1416 = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
1417
1418 tcIfaceExpr (IfaceECase scrut ty)
1419 = do { scrut' <- tcIfaceExpr scrut
1420 ; ty' <- tcIfaceType ty
1421 ; return (castBottomExpr scrut' ty') }
1422
1423 tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
1424 scrut' <- tcIfaceExpr scrut
1425 case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
1426 let
1427 scrut_ty = exprType scrut'
1428 case_bndr' = mkLocalIdOrCoVar case_bndr_name scrut_ty
1429 tc_app = splitTyConApp scrut_ty
1430 -- NB: Won't always succeed (polymorphic case)
1431 -- but won't be demanded in those cases
1432 -- NB: not tcSplitTyConApp; we are looking at Core here
1433 -- look through non-rec newtypes to find the tycon that
1434 -- corresponds to the datacon in this case alternative
1435
1436 extendIfaceIdEnv [case_bndr'] $ do
1437 alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
1438 return (Case scrut' case_bndr' (coreAltsType alts') alts')
1439
1440 tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info ji) rhs) body)
1441 = do { name <- newIfaceName (mkVarOccFS fs)
1442 ; ty' <- tcIfaceType ty
1443 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1444 name ty' info
1445 ; let id = mkLocalIdOrCoVarWithInfo name ty' id_info
1446 `asJoinId_maybe` tcJoinInfo ji
1447 ; rhs' <- tcIfaceExpr rhs
1448 ; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
1449 ; return (Let (NonRec id rhs') body') }
1450
1451 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
1452 = do { ids <- mapM tc_rec_bndr (map fst pairs)
1453 ; extendIfaceIdEnv ids $ do
1454 { pairs' <- zipWithM tc_pair pairs ids
1455 ; body' <- tcIfaceExpr body
1456 ; return (Let (Rec pairs') body') } }
1457 where
1458 tc_rec_bndr (IfLetBndr fs ty _ ji)
1459 = do { name <- newIfaceName (mkVarOccFS fs)
1460 ; ty' <- tcIfaceType ty
1461 ; return (mkLocalIdOrCoVar name ty' `asJoinId_maybe` tcJoinInfo ji) }
1462 tc_pair (IfLetBndr _ _ info _, rhs) id
1463 = do { rhs' <- tcIfaceExpr rhs
1464 ; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
1465 (idName id) (idType id) info
1466 ; return (setIdInfo id id_info, rhs') }
1467
1468 tcIfaceExpr (IfaceTick tickish expr) = do
1469 expr' <- tcIfaceExpr expr
1470 -- If debug flag is not set: Ignore source notes
1471 dbgLvl <- fmap debugLevel getDynFlags
1472 case tickish of
1473 IfaceSource{} | dbgLvl > 0
1474 -> return expr'
1475 _otherwise -> do
1476 tickish' <- tcIfaceTickish tickish
1477 return (Tick tickish' expr')
1478
1479 -------------------------
1480 tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
1481 tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
1482 tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
1483 tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
1484
1485 -------------------------
1486 tcIfaceLit :: Literal -> IfL Literal
1487 -- Integer literals deserialise to (LitInteger i <error thunk>)
1488 -- so tcIfaceLit just fills in the type.
1489 -- See Note [Integer literals] in Literal
1490 tcIfaceLit (LitInteger i _)
1491 = do t <- tcIfaceTyConByName integerTyConName
1492 return (mkLitInteger i (mkTyConTy t))
1493 tcIfaceLit lit = return lit
1494
1495 -------------------------
1496 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
1497 -> (IfaceConAlt, [FastString], IfaceExpr)
1498 -> IfL (AltCon, [TyVar], CoreExpr)
1499 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
1500 = ASSERT( null names ) do
1501 rhs' <- tcIfaceExpr rhs
1502 return (DEFAULT, [], rhs')
1503
1504 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
1505 = ASSERT( null names ) do
1506 lit' <- tcIfaceLit lit
1507 rhs' <- tcIfaceExpr rhs
1508 return (LitAlt lit', [], rhs')
1509
1510 -- A case alternative is made quite a bit more complicated
1511 -- by the fact that we omit type annotations because we can
1512 -- work them out. True enough, but its not that easy!
1513 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
1514 = do { con <- tcIfaceDataCon data_occ
1515 ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
1516 (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
1517 ; tcIfaceDataAlt con inst_tys arg_strs rhs }
1518
1519 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
1520 -> IfL (AltCon, [TyVar], CoreExpr)
1521 tcIfaceDataAlt con inst_tys arg_strs rhs
1522 = do { us <- newUniqueSupply
1523 ; let uniqs = uniqsFromSupply us
1524 ; let (ex_tvs, arg_ids)
1525 = dataConRepFSInstPat arg_strs uniqs con inst_tys
1526
1527 ; rhs' <- extendIfaceEnvs ex_tvs $
1528 extendIfaceIdEnv arg_ids $
1529 tcIfaceExpr rhs
1530 ; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
1531
1532 {-
1533 ************************************************************************
1534 * *
1535 IdInfo
1536 * *
1537 ************************************************************************
1538 -}
1539
1540 tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
1541 tcIdDetails _ IfVanillaId = return VanillaId
1542 tcIdDetails ty IfDFunId
1543 = return (DFunId (isNewTyCon (classTyCon cls)))
1544 where
1545 (_, _, cls, _) = tcSplitDFunTy ty
1546
1547 tcIdDetails _ (IfRecSelId tc naughty)
1548 = do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
1549 (fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
1550 tc
1551 ; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
1552 where
1553 tyThingPatSyn (AConLike (PatSynCon ps)) = ps
1554 tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
1555
1556 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
1557 tcIdInfo ignore_prags name ty info = do
1558 lcl_env <- getLclEnv
1559 -- Set the CgInfo to something sensible but uninformative before
1560 -- we start; default assumption is that it has CAFs
1561 let init_info | if_boot lcl_env = vanillaIdInfo `setUnfoldingInfo` BootUnfolding
1562 | otherwise = vanillaIdInfo
1563 if ignore_prags
1564 then return init_info
1565 else case info of
1566 NoInfo -> return init_info
1567 HasInfo info -> foldlM tcPrag init_info info
1568 where
1569 tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
1570 tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
1571 tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
1572 tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
1573 tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
1574 tcPrag info HsLevity = return (info `setNeverLevPoly` ty)
1575
1576 -- The next two are lazy, so they don't transitively suck stuff in
1577 tcPrag info (HsUnfold lb if_unf)
1578 = do { unf <- tcUnfolding name ty info if_unf
1579 ; let info1 | lb = info `setOccInfo` strongLoopBreaker
1580 | otherwise = info
1581 ; return (info1 `setUnfoldingInfo` unf) }
1582
1583 tcJoinInfo :: IfaceJoinInfo -> Maybe JoinArity
1584 tcJoinInfo (IfaceJoinPoint ar) = Just ar
1585 tcJoinInfo IfaceNotJoinPoint = Nothing
1586
1587 tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
1588 tcUnfolding name _ info (IfCoreUnfold stable if_expr)
1589 = do { dflags <- getDynFlags
1590 ; mb_expr <- tcPragExpr name if_expr
1591 ; let unf_src | stable = InlineStable
1592 | otherwise = InlineRhs
1593 ; return $ case mb_expr of
1594 Nothing -> NoUnfolding
1595 Just expr -> mkUnfolding dflags unf_src
1596 True {- Top level -}
1597 (isBottomingSig strict_sig)
1598 expr
1599 }
1600 where
1601 -- Strictness should occur before unfolding!
1602 strict_sig = strictnessInfo info
1603 tcUnfolding name _ _ (IfCompulsory if_expr)
1604 = do { mb_expr <- tcPragExpr name if_expr
1605 ; return (case mb_expr of
1606 Nothing -> NoUnfolding
1607 Just expr -> mkCompulsoryUnfolding expr) }
1608
1609 tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
1610 = do { mb_expr <- tcPragExpr name if_expr
1611 ; return (case mb_expr of
1612 Nothing -> NoUnfolding
1613 Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
1614 where
1615 guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
1616
1617 tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
1618 = bindIfaceBndrs bs $ \ bs' ->
1619 do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
1620 ; return (case mb_ops1 of
1621 Nothing -> noUnfolding
1622 Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
1623 where
1624 doc = text "Class ops for dfun" <+> ppr name
1625 (_, _, cls, _) = tcSplitDFunTy dfun_ty
1626
1627 {-
1628 For unfoldings we try to do the job lazily, so that we never type check
1629 an unfolding that isn't going to be looked at.
1630 -}
1631
1632 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
1633 tcPragExpr name expr
1634 = forkM_maybe doc $ do
1635 core_expr' <- tcIfaceExpr expr
1636
1637 -- Check for type consistency in the unfolding
1638 whenGOptM Opt_DoCoreLinting $ do
1639 in_scope <- get_in_scope
1640 dflags <- getDynFlags
1641 case lintUnfolding dflags noSrcLoc in_scope core_expr' of
1642 Nothing -> return ()
1643 Just fail_msg -> do { mod <- getIfModule
1644 ; pprPanic "Iface Lint failure"
1645 (vcat [ text "In interface for" <+> ppr mod
1646 , hang doc 2 fail_msg
1647 , ppr name <+> equals <+> ppr core_expr'
1648 , text "Iface expr =" <+> ppr expr ]) }
1649 return core_expr'
1650 where
1651 doc = text "Unfolding of" <+> ppr name
1652
1653 get_in_scope :: IfL VarSet -- Totally disgusting; but just for linting
1654 get_in_scope
1655 = do { (gbl_env, lcl_env) <- getEnvs
1656 ; rec_ids <- case if_rec_types gbl_env of
1657 Nothing -> return []
1658 Just (_, get_env) -> do
1659 { type_env <- setLclEnv () get_env
1660 ; return (typeEnvIds type_env) }
1661 ; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
1662 bindingsVars (if_id_env lcl_env) `unionVarSet`
1663 mkVarSet rec_ids) }
1664
1665 bindingsVars :: FastStringEnv Var -> VarSet
1666 bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
1667 -- It's OK to use nonDetEltsUFM here because we immediately forget
1668 -- the ordering by creating a set
1669
1670 {-
1671 ************************************************************************
1672 * *
1673 Getting from Names to TyThings
1674 * *
1675 ************************************************************************
1676 -}
1677
1678 tcIfaceGlobal :: Name -> IfL TyThing
1679 tcIfaceGlobal name
1680 | Just thing <- wiredInNameTyThing_maybe name
1681 -- Wired-in things include TyCons, DataCons, and Ids
1682 -- Even though we are in an interface file, we want to make
1683 -- sure the instances and RULES of this thing (particularly TyCon) are loaded
1684 -- Imagine: f :: Double -> Double
1685 = do { ifCheckWiredInThing thing; return thing }
1686
1687 | otherwise
1688 = do { env <- getGblEnv
1689 ; case if_rec_types env of { -- Note [Tying the knot]
1690 Just (mod, get_type_env)
1691 | nameIsLocalOrFrom mod name
1692 -> do -- It's defined in the module being compiled
1693 { type_env <- setLclEnv () get_type_env -- yuk
1694 ; case lookupNameEnv type_env name of
1695 Just thing -> return thing
1696 Nothing ->
1697 pprPanic "tcIfaceGlobal (local): not found"
1698 (ifKnotErr name (if_doc env) type_env)
1699 }
1700
1701 ; _ -> do
1702
1703 { hsc_env <- getTopEnv
1704 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1705 ; case mb_thing of {
1706 Just thing -> return thing ;
1707 Nothing -> do
1708
1709 { mb_thing <- importDecl name -- It's imported; go get it
1710 ; case mb_thing of
1711 Failed err -> failIfM err
1712 Succeeded thing -> return thing
1713 }}}}}
1714
1715 ifKnotErr :: Name -> SDoc -> TypeEnv -> SDoc
1716 ifKnotErr name env_doc type_env = vcat
1717 [ text "You are in a maze of twisty little passages, all alike."
1718 , text "While forcing the thunk for TyThing" <+> ppr name
1719 , text "which was lazily initialized by" <+> env_doc <> text ","
1720 , text "I tried to tie the knot, but I couldn't find" <+> ppr name
1721 , text "in the current type environment."
1722 , text "If you are developing GHC, please read Note [Tying the knot]"
1723 , text "and Note [Type-checking inside the knot]."
1724 , text "Consider rebuilding GHC with profiling for a better stack trace."
1725 , hang (text "Contents of current type environment:")
1726 2 (ppr type_env)
1727 ]
1728
1729 -- Note [Tying the knot]
1730 -- ~~~~~~~~~~~~~~~~~~~~~
1731 -- The if_rec_types field is used when we are compiling M.hs, which indirectly
1732 -- imports Foo.hi, which mentions M.T Then we look up M.T in M's type
1733 -- environment, which is splatted into if_rec_types after we've built M's type
1734 -- envt.
1735 --
1736 -- This is a dark and complicated part of GHC type checking, with a lot
1737 -- of moving parts. Interested readers should also look at:
1738 --
1739 -- * Note [Knot-tying typecheckIface]
1740 -- * Note [DFun knot-tying]
1741 -- * Note [hsc_type_env_var hack]
1742 --
1743 -- There is also a wiki page on the subject, see:
1744 --
1745 -- https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TyingTheKnot
1746
1747 tcIfaceTyConByName :: IfExtName -> IfL TyCon
1748 tcIfaceTyConByName name
1749 = do { thing <- tcIfaceGlobal name
1750 ; return (tyThingTyCon thing) }
1751
1752 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1753 tcIfaceTyCon (IfaceTyCon name info)
1754 = do { thing <- tcIfaceGlobal name
1755 ; return $ case ifaceTyConIsPromoted info of
1756 IsNotPromoted -> tyThingTyCon thing
1757 IsPromoted -> promoteDataCon $ tyThingDataCon thing }
1758
1759 tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
1760 tcIfaceCoAxiom name = do { thing <- tcIfaceImplicit name
1761 ; return (tyThingCoAxiom thing) }
1762
1763 tcIfaceDataCon :: Name -> IfL DataCon
1764 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1765 ; case thing of
1766 AConLike (RealDataCon dc) -> return dc
1767 _ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1768
1769 tcIfaceExtId :: Name -> IfL Id
1770 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1771 ; case thing of
1772 AnId id -> return id
1773 _ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1774
1775 -- See Note [Resolving never-exported Names in TcIface]
1776 tcIfaceImplicit :: Name -> IfL TyThing
1777 tcIfaceImplicit n = do
1778 lcl_env <- getLclEnv
1779 case if_implicits_env lcl_env of
1780 Nothing -> tcIfaceGlobal n
1781 Just tenv ->
1782 case lookupTypeEnv tenv n of
1783 Nothing -> pprPanic "tcIfaceInst" (ppr n $$ ppr tenv)
1784 Just tything -> return tything
1785
1786 {-
1787 ************************************************************************
1788 * *
1789 Bindings
1790 * *
1791 ************************************************************************
1792 -}
1793
1794 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
1795 bindIfaceId (fs, ty) thing_inside
1796 = do { name <- newIfaceName (mkVarOccFS fs)
1797 ; ty' <- tcIfaceType ty
1798 ; let id = mkLocalIdOrCoVar name ty'
1799 ; extendIfaceIdEnv [id] (thing_inside id) }
1800
1801 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
1802 bindIfaceIds [] thing_inside = thing_inside []
1803 bindIfaceIds (b:bs) thing_inside
1804 = bindIfaceId b $ \b' ->
1805 bindIfaceIds bs $ \bs' ->
1806 thing_inside (b':bs')
1807
1808 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1809 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
1810 = bindIfaceId bndr thing_inside
1811 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1812 = bindIfaceTyVar bndr thing_inside
1813
1814 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1815 bindIfaceBndrs [] thing_inside = thing_inside []
1816 bindIfaceBndrs (b:bs) thing_inside
1817 = bindIfaceBndr b $ \ b' ->
1818 bindIfaceBndrs bs $ \ bs' ->
1819 thing_inside (b':bs')
1820
1821 -----------------------
1822 bindIfaceForAllBndrs :: [IfaceForAllBndr] -> ([TyVarBinder] -> IfL a) -> IfL a
1823 bindIfaceForAllBndrs [] thing_inside = thing_inside []
1824 bindIfaceForAllBndrs (bndr:bndrs) thing_inside
1825 = bindIfaceForAllBndr bndr $ \tv vis ->
1826 bindIfaceForAllBndrs bndrs $ \bndrs' ->
1827 thing_inside (mkTyVarBinder vis tv : bndrs')
1828
1829 bindIfaceForAllBndr :: IfaceForAllBndr -> (TyVar -> ArgFlag -> IfL a) -> IfL a
1830 bindIfaceForAllBndr (TvBndr tv vis) thing_inside
1831 = bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
1832
1833 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1834 bindIfaceTyVar (occ,kind) thing_inside
1835 = do { name <- newIfaceName (mkTyVarOccFS occ)
1836 ; tyvar <- mk_iface_tyvar name kind
1837 ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1838
1839 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1840 mk_iface_tyvar name ifKind
1841 = do { kind <- tcIfaceType ifKind
1842 ; return (Var.mkTyVar name kind) }
1843
1844 bindIfaceTyConBinders :: [IfaceTyConBinder]
1845 -> ([TyConBinder] -> IfL a) -> IfL a
1846 bindIfaceTyConBinders [] thing_inside = thing_inside []
1847 bindIfaceTyConBinders (b:bs) thing_inside
1848 = bindIfaceTyConBinderX bindIfaceTyVar b $ \ b' ->
1849 bindIfaceTyConBinders bs $ \ bs' ->
1850 thing_inside (b':bs')
1851
1852 bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
1853 -> ([TyConBinder] -> IfL a) -> IfL a
1854 -- Used for type variable in nested associated data/type declarations
1855 -- where some of the type variables are already in scope
1856 -- class C a where { data T a b }
1857 -- Here 'a' is in scope when we look at the 'data T'
1858 bindIfaceTyConBinders_AT [] thing_inside
1859 = thing_inside []
1860 bindIfaceTyConBinders_AT (b : bs) thing_inside
1861 = bindIfaceTyConBinderX bind_tv b $ \b' ->
1862 bindIfaceTyConBinders_AT bs $ \bs' ->
1863 thing_inside (b':bs')
1864 where
1865 bind_tv tv thing
1866 = do { mb_tv <- lookupIfaceTyVar tv
1867 ; case mb_tv of
1868 Just b' -> thing b'
1869 Nothing -> bindIfaceTyVar tv thing }
1870
1871 bindIfaceTyConBinderX :: (IfaceTvBndr -> (TyVar -> IfL a) -> IfL a)
1872 -> IfaceTyConBinder
1873 -> (TyConBinder -> IfL a) -> IfL a
1874 bindIfaceTyConBinderX bind_tv (TvBndr tv vis) thing_inside
1875 = bind_tv tv $ \tv' ->
1876 thing_inside (TvBndr tv' vis)