28b03119acf456812e292b7d72d30d03346fd9cd
[ghc-hetmet.git] / compiler / iface / TcIface.lhs
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 \begin{code}
9 module TcIface ( 
10         tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface, 
11         tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
12         tcIfaceVectInfo, tcIfaceAnnotations, tcIfaceGlobal, tcExtCoreBindings
13  ) where
14
15 #include "HsVersions.h"
16
17 import IfaceSyn
18 import LoadIface
19 import IfaceEnv
20 import BuildTyCl
21 import TcRnMonad
22 import Type
23 import TypeRep
24 import HscTypes
25 import Annotations
26 import InstEnv
27 import FamInstEnv
28 import CoreSyn
29 import CoreUtils
30 import CoreUnfold
31 import CoreLint
32 import WorkWrap
33 import Id
34 import MkId
35 import IdInfo
36 import Class
37 import TyCon
38 import DataCon
39 import TysWiredIn
40 import Var              ( TyVar )
41 import qualified Var
42 import VarEnv
43 import Name
44 import NameEnv
45 import OccName
46 import Module
47 import LazyUniqFM
48 import UniqSupply
49 import Outputable       
50 import ErrUtils
51 import Maybes
52 import SrcLoc
53 import DynFlags
54 import Util
55 import FastString
56 import BasicTypes (Arity)
57
58 import Control.Monad
59 import Data.List
60 import Data.Maybe
61 \end{code}
62
63 This module takes
64
65         IfaceDecl -> TyThing
66         IfaceType -> Type
67         etc
68
69 An IfaceDecl is populated with RdrNames, and these are not renamed to
70 Names before typechecking, because there should be no scope errors etc.
71
72         -- For (b) consider: f = \$(...h....)
73         -- where h is imported, and calls f via an hi-boot file.  
74         -- This is bad!  But it is not seen as a staging error, because h
75         -- is indeed imported.  We don't want the type-checker to black-hole 
76         -- when simplifying and compiling the splice!
77         --
78         -- Simple solution: discard any unfolding that mentions a variable
79         -- bound in this module (and hence not yet processed).
80         -- The discarding happens when forkM finds a type error.
81
82 %************************************************************************
83 %*                                                                      *
84 %*      tcImportDecl is the key function for "faulting in"              *
85 %*      imported things
86 %*                                                                      *
87 %************************************************************************
88
89 The main idea is this.  We are chugging along type-checking source code, and
90 find a reference to GHC.Base.map.  We call tcLookupGlobal, which doesn't find
91 it in the EPS type envt.  So it 
92         1 loads GHC.Base.hi
93         2 gets the decl for GHC.Base.map
94         3 typechecks it via tcIfaceDecl
95         4 and adds it to the type env in the EPS
96
97 Note that DURING STEP 4, we may find that map's type mentions a type 
98 constructor that also 
99
100 Notice that for imported things we read the current version from the EPS
101 mutable variable.  This is important in situations like
102         ...$(e1)...$(e2)...
103 where the code that e1 expands to might import some defns that 
104 also turn out to be needed by the code that e2 expands to.
105
106 \begin{code}
107 tcImportDecl :: Name -> TcM TyThing
108 -- Entry point for *source-code* uses of importDecl
109 tcImportDecl name 
110   | Just thing <- wiredInNameTyThing_maybe name
111   = do  { initIfaceTcRn (loadWiredInHomeIface name) 
112                 -- See Note [Loading instances] in LoadIface
113         ; return thing }
114   | otherwise
115   = do  { traceIf (text "tcImportDecl" <+> ppr name)
116         ; mb_thing <- initIfaceTcRn (importDecl name)
117         ; case mb_thing of
118             Succeeded thing -> return thing
119             Failed err      -> failWithTc err }
120
121 checkWiredInTyCon :: TyCon -> TcM ()
122 -- Ensure that the home module of the TyCon (and hence its instances)
123 -- are loaded. See See Note [Loading instances] in LoadIface
124 -- It might not be a wired-in tycon (see the calls in TcUnify),
125 -- in which case this is a no-op.
126 checkWiredInTyCon tc    
127   | not (isWiredInName tc_name) 
128   = return ()
129   | otherwise
130   = do  { mod <- getModule
131         ; ASSERT( isExternalName tc_name ) 
132           unless (mod == nameModule tc_name)
133                  (initIfaceTcRn (loadWiredInHomeIface tc_name))
134                 -- Don't look for (non-existent) Float.hi when
135                 -- compiling Float.lhs, which mentions Float of course
136                 -- A bit yukky to call initIfaceTcRn here
137         }
138   where
139     tc_name = tyConName tc
140
141 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
142 -- Get the TyThing for this Name from an interface file
143 -- It's not a wired-in thing -- the caller caught that
144 importDecl name
145   = ASSERT( not (isWiredInName name) )
146     do  { traceIf nd_doc
147
148         -- Load the interface, which should populate the PTE
149         ; mb_iface <- ASSERT2( isExternalName name, ppr name ) 
150                       loadInterface nd_doc (nameModule name) ImportBySystem
151         ; case mb_iface of {
152                 Failed err_msg  -> return (Failed err_msg) ;
153                 Succeeded _ -> do
154
155         -- Now look it up again; this time we should find it
156         { eps <- getEps 
157         ; case lookupTypeEnv (eps_PTE eps) name of
158             Just thing -> return (Succeeded thing)
159             Nothing    -> return (Failed not_found_msg)
160     }}}
161   where
162     nd_doc = ptext (sLit "Need decl for") <+> ppr name
163     not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
164                                 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
165                        2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
166                                 ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
167 \end{code}
168
169 %************************************************************************
170 %*                                                                      *
171                 Type-checking a complete interface
172 %*                                                                      *
173 %************************************************************************
174
175 Suppose we discover we don't need to recompile.  Then we must type
176 check the old interface file.  This is a bit different to the
177 incremental type checking we do as we suck in interface files.  Instead
178 we do things similarly as when we are typechecking source decls: we
179 bring into scope the type envt for the interface all at once, using a
180 knot.  Remember, the decls aren't necessarily in dependency order --
181 and even if they were, the type decls might be mutually recursive.
182
183 \begin{code}
184 typecheckIface :: ModIface      -- Get the decls from here
185                -> TcRnIf gbl lcl ModDetails
186 typecheckIface iface
187   = initIfaceTc iface $ \ tc_env_var -> do
188         -- The tc_env_var is freshly allocated, private to 
189         -- type-checking this particular interface
190         {       -- Get the right set of decls and rules.  If we are compiling without -O
191                 -- we discard pragmas before typechecking, so that we don't "see"
192                 -- information that we shouldn't.  From a versioning point of view
193                 -- It's not actually *wrong* to do so, but in fact GHCi is unable 
194                 -- to handle unboxed tuples, so it must not see unfoldings.
195           ignore_prags <- doptM Opt_IgnoreInterfacePragmas
196
197                 -- Typecheck the decls.  This is done lazily, so that the knot-tying
198                 -- within this single module work out right.  In the If monad there is
199                 -- no global envt for the current interface; instead, the knot is tied
200                 -- through the if_rec_types field of IfGblEnv
201         ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
202         ; let type_env = mkNameEnv names_w_things
203         ; writeMutVar tc_env_var type_env
204
205                 -- Now do those rules, instances and annotations
206         ; insts     <- mapM tcIfaceInst    (mi_insts     iface)
207         ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
208         ; rules     <- tcIfaceRules ignore_prags (mi_rules iface)
209         ; anns      <- tcIfaceAnnotations  (mi_anns iface)
210
211                 -- Vectorisation information
212         ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env 
213                                        (mi_vect_info iface)
214
215                 -- Exports
216         ; exports <- ifaceExportNames (mi_exports iface)
217
218                 -- Finished
219         ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
220                          text "Type envt:" <+> ppr type_env])
221         ; return $ ModDetails { md_types     = type_env
222                               , md_insts     = insts
223                               , md_fam_insts = fam_insts
224                               , md_rules     = rules
225                               , md_anns      = anns
226                               , md_vect_info = vect_info
227                               , md_exports   = exports
228                               }
229     }
230 \end{code}
231
232
233 %************************************************************************
234 %*                                                                      *
235                 Type and class declarations
236 %*                                                                      *
237 %************************************************************************
238
239 \begin{code}
240 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
241 -- Load the hi-boot iface for the module being compiled,
242 -- if it indeed exists in the transitive closure of imports
243 -- Return the ModDetails, empty if no hi-boot iface
244 tcHiBootIface hsc_src mod
245   | isHsBoot hsc_src            -- Already compiling a hs-boot file
246   = return emptyModDetails
247   | otherwise
248   = do  { traceIf (text "loadHiBootInterface" <+> ppr mod)
249
250         ; mode <- getGhcMode
251         ; if not (isOneShot mode)
252                 -- In --make and interactive mode, if this module has an hs-boot file
253                 -- we'll have compiled it already, and it'll be in the HPT
254                 -- 
255                 -- We check wheher the interface is a *boot* interface.
256                 -- It can happen (when using GHC from Visual Studio) that we
257                 -- compile a module in TypecheckOnly mode, with a stable, 
258                 -- fully-populated HPT.  In that case the boot interface isn't there
259                 -- (it's been replaced by the mother module) so we can't check it.
260                 -- And that's fine, because if M's ModInfo is in the HPT, then 
261                 -- it's been compiled once, and we don't need to check the boot iface
262           then do { hpt <- getHpt
263                   ; case lookupUFM hpt (moduleName mod) of
264                       Just info | mi_boot (hm_iface info) 
265                                 -> return (hm_details info)
266                       _ -> return emptyModDetails }
267           else do
268
269         -- OK, so we're in one-shot mode.  
270         -- In that case, we're read all the direct imports by now, 
271         -- so eps_is_boot will record if any of our imports mention us by 
272         -- way of hi-boot file
273         { eps <- getEps
274         ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
275             Nothing -> return emptyModDetails ; -- The typical case
276
277             Just (_, False) -> failWithTc moduleLoop ;
278                 -- Someone below us imported us!
279                 -- This is a loop with no hi-boot in the way
280                 
281             Just (_mod, True) ->        -- There's a hi-boot interface below us
282                 
283     do  { read_result <- findAndReadIface 
284                                 need mod
285                                 True    -- Hi-boot file
286
287         ; case read_result of
288                 Failed err               -> failWithTc (elaborate err)
289                 Succeeded (iface, _path) -> typecheckIface iface
290     }}}}
291   where
292     need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
293                  <+> ptext (sLit "to compare against the Real Thing")
294
295     moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod) 
296                      <+> ptext (sLit "depends on itself")
297
298     elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+> 
299                           quotes (ppr mod) <> colon) 4 err
300 \end{code}
301
302
303 %************************************************************************
304 %*                                                                      *
305                 Type and class declarations
306 %*                                                                      *
307 %************************************************************************
308
309 When typechecking a data type decl, we *lazily* (via forkM) typecheck
310 the constructor argument types.  This is in the hope that we may never
311 poke on those argument types, and hence may never need to load the
312 interface files for types mentioned in the arg types.
313
314 E.g.    
315         data Foo.S = MkS Baz.T
316 Mabye we can get away without even loading the interface for Baz!
317
318 This is not just a performance thing.  Suppose we have
319         data Foo.S = MkS Baz.T
320         data Baz.T = MkT Foo.S
321 (in different interface files, of course).
322 Now, first we load and typecheck Foo.S, and add it to the type envt.  
323 If we do explore MkS's argument, we'll load and typecheck Baz.T.
324 If we explore MkT's argument we'll find Foo.S already in the envt.  
325
326 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
327 typecheck the type Baz.T.  So we'd fault in Baz.T... and then need Foo.S...
328 which isn't done yet.
329
330 All very cunning. However, there is a rather subtle gotcha which bit
331 me when developing this stuff.  When we typecheck the decl for S, we
332 extend the type envt with S, MkS, and all its implicit Ids.  Suppose
333 (a bug, but it happened) that the list of implicit Ids depended in
334 turn on the constructor arg types.  Then the following sequence of
335 events takes place:
336         * we build a thunk <t> for the constructor arg tys
337         * we build a thunk for the extended type environment (depends on <t>)
338         * we write the extended type envt into the global EPS mutvar
339         
340 Now we look something up in the type envt
341         * that pulls on <t>
342         * which reads the global type envt out of the global EPS mutvar
343         * but that depends in turn on <t>
344
345 It's subtle, because, it'd work fine if we typechecked the constructor args 
346 eagerly -- they don't need the extended type envt.  They just get the extended
347 type envt by accident, because they look at it later.
348
349 What this means is that the implicitTyThings MUST NOT DEPEND on any of
350 the forkM stuff.
351
352
353 \begin{code}
354 tcIfaceDecl :: Bool     -- True <=> discard IdInfo on IfaceId bindings
355             -> IfaceDecl
356             -> IfL TyThing
357
358 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
359   = do  { name <- lookupIfaceTop occ_name
360         ; ty <- tcIfaceType iface_type
361         ; info <- tcIdInfo ignore_prags name ty info
362         ; return (AnId (mkVanillaGlobalWithInfo name ty info)) }
363
364 tcIfaceDecl _ (IfaceData {ifName = occ_name, 
365                           ifTyVars = tv_bndrs, 
366                           ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
367                           ifCons = rdr_cons, 
368                           ifRec = is_rec, 
369                           ifGeneric = want_generic,
370                           ifFamInst = mb_family })
371   = do  { tc_name <- lookupIfaceTop occ_name
372         ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
373
374         { tycon <- fixM ( \ tycon -> do
375             { stupid_theta <- tcIfaceCtxt ctxt
376             ; famInst <- 
377                 case mb_family of
378                   Nothing         -> return Nothing
379                   Just (fam, tys) -> 
380                     do { famTyCon <- tcIfaceTyCon fam
381                        ; insttys <- mapM tcIfaceType tys
382                        ; return $ Just (famTyCon, insttys)
383                        }
384             ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
385             ; buildAlgTyCon tc_name tyvars stupid_theta
386                             cons is_rec want_generic gadt_syn famInst
387             })
388         ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
389         ; return (ATyCon tycon)
390     }}
391
392 tcIfaceDecl _ (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs, 
393                          ifSynRhs = mb_rhs_ty,
394                          ifSynKind = kind, ifFamInst = mb_family})
395    = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
396      { tc_name <- lookupIfaceTop occ_name
397      ; rhs_kind <- tcIfaceType kind     -- Note [Synonym kind loop]
398      ; ~(rhs, fam) <- forkM (mk_doc tc_name) $ 
399                       do { rhs <- tc_syn_rhs rhs_kind mb_rhs_ty
400                          ; fam <- tc_syn_fam mb_family
401                          ; return (rhs, fam) }
402      ; tycon <- buildSynTyCon tc_name tyvars rhs rhs_kind fam
403      ; return $ ATyCon tycon
404      }
405    where
406      mk_doc n = ptext (sLit "Type syonym") <+> ppr n
407      tc_syn_rhs kind Nothing   = return (OpenSynTyCon kind Nothing)
408      tc_syn_rhs _    (Just ty) = do { rhs_ty <- tcIfaceType ty
409                                     ; return (SynonymTyCon rhs_ty) }
410      tc_syn_fam Nothing 
411        = return Nothing
412      tc_syn_fam (Just (fam, tys)) 
413        = do { famTyCon <- tcIfaceTyCon fam
414             ; insttys <- mapM tcIfaceType tys
415             ; return $ Just (famTyCon, insttys) }
416
417 tcIfaceDecl ignore_prags
418             (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, 
419                          ifTyVars = tv_bndrs, ifFDs = rdr_fds, 
420                          ifATs = rdr_ats, ifSigs = rdr_sigs, 
421                          ifRec = tc_isrec })
422 -- ToDo: in hs-boot files we should really treat abstract classes specially,
423 --       as we do abstract tycons
424   = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
425     { cls_name <- lookupIfaceTop occ_name
426     ; ctxt <- tcIfaceCtxt rdr_ctxt
427     ; sigs <- mapM tc_sig rdr_sigs
428     ; fds  <- mapM tc_fd rdr_fds
429     ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
430     ; let ats = map (setAssocFamilyPermutation tyvars) ats'
431     ; cls  <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
432     ; return (AClass cls) }
433   where
434    tc_sig (IfaceClassOp occ dm rdr_ty)
435      = do { op_name <- lookupIfaceTop occ
436           ; op_ty   <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
437                 -- Must be done lazily for just the same reason as the 
438                 -- type of a data con; to avoid sucking in types that
439                 -- it mentions unless it's necessray to do so
440           ; return (op_name, dm, op_ty) }
441
442    mk_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
443
444    tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
445                            ; tvs2' <- mapM tcIfaceTyVar tvs2
446                            ; return (tvs1', tvs2') }
447
448 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
449   = do  { name <- lookupIfaceTop rdr_name
450         ; return (ATyCon (mkForeignTyCon name ext_name 
451                                          liftedTypeKind 0)) }
452
453 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
454 tcIfaceDataCons tycon_name tycon _ if_cons
455   = case if_cons of
456         IfAbstractTyCon  -> return mkAbstractTyConRhs
457         IfOpenDataTyCon  -> return mkOpenDataTyConRhs
458         IfDataTyCon cons -> do  { data_cons <- mapM tc_con_decl cons
459                                 ; return (mkDataTyConRhs data_cons) }
460         IfNewTyCon con   -> do  { data_con <- tc_con_decl con
461                                 ; mkNewTyConRhs tycon_name tycon data_con }
462   where
463     tc_con_decl (IfCon { ifConInfix = is_infix, 
464                          ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
465                          ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
466                          ifConArgTys = args, ifConFields = field_lbls,
467                          ifConStricts = stricts})
468      = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
469        bindIfaceTyVars ex_tvs    $ \ ex_tyvars -> do
470         { name  <- lookupIfaceTop occ
471         ; eq_spec <- tcIfaceEqSpec spec
472         ; theta <- tcIfaceCtxt ctxt     -- Laziness seems not worth the bother here
473                 -- At one stage I thought that this context checking *had*
474                 -- to be lazy, because of possible mutual recursion between the
475                 -- type and the classe: 
476                 -- E.g. 
477                 --      class Real a where { toRat :: a -> Ratio Integer }
478                 --      data (Real a) => Ratio a = ...
479                 -- But now I think that the laziness in checking class ops breaks 
480                 -- the loop, so no laziness needed
481
482         -- Read the argument types, but lazily to avoid faulting in
483         -- the component types unless they are really needed
484         ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
485         ; lbl_names <- mapM lookupIfaceTop field_lbls
486
487         -- Remember, tycon is the representation tycon
488         ; let orig_res_ty = mkFamilyTyConApp tycon 
489                                 (substTyVars (mkTopTvSubst eq_spec) univ_tyvars)
490
491         ; buildDataCon name is_infix {- Not infix -}
492                        stricts lbl_names
493                        univ_tyvars ex_tyvars 
494                        eq_spec theta 
495                        arg_tys orig_res_ty tycon
496         }
497     mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
498
499 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
500 tcIfaceEqSpec spec
501   = mapM do_item spec
502   where
503     do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
504                               ; ty <- tcIfaceType if_ty
505                               ; return (tv,ty) }
506 \end{code}
507
508 Note [Synonym kind loop]
509 ~~~~~~~~~~~~~~~~~~~~~~~~
510 Notice that we eagerly grab the *kind* from the interface file, but
511 build a forkM thunk for the *rhs* (and family stuff).  To see why, 
512 consider this (Trac #2412)
513
514 M.hs:       module M where { import X; data T = MkT S }
515 X.hs:       module X where { import {-# SOURCE #-} M; type S = T }
516 M.hs-boot:  module M where { data T }
517
518 When kind-checking M.hs we need S's kind.  But we do not want to
519 find S's kind from (typeKind S-rhs), because we don't want to look at
520 S-rhs yet!  Since S is imported from X.hi, S gets just one chance to
521 be defined, and we must not do that until we've finished with M.T.
522
523 Solution: record S's kind in the interface file; now we can safely
524 look at it.
525
526 %************************************************************************
527 %*                                                                      *
528                 Instances
529 %*                                                                      *
530 %************************************************************************
531
532 \begin{code}
533 tcIfaceInst :: IfaceInst -> IfL Instance
534 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
535                          ifInstCls = cls, ifInstTys = mb_tcs })
536   = do  { dfun    <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
537                      tcIfaceExtId dfun_occ
538         ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
539         ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
540
541 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
542 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon, 
543                                ifFamInstFam = fam, ifFamInstTys = mb_tcs })
544 --      { tycon'  <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
545 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
546     = do tycon'  <- forkM (text ("Inst tycon") <+> ppr tycon) $
547                     tcIfaceTyCon tycon
548          let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
549          return (mkImportedFamInst fam mb_tcs' tycon')
550 \end{code}
551
552
553 %************************************************************************
554 %*                                                                      *
555                 Rules
556 %*                                                                      *
557 %************************************************************************
558
559 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
560 are in the type environment.  However, remember that typechecking a Rule may 
561 (as a side effect) augment the type envt, and so we may need to iterate the process.
562
563 \begin{code}
564 tcIfaceRules :: Bool            -- True <=> ignore rules
565              -> [IfaceRule]
566              -> IfL [CoreRule]
567 tcIfaceRules ignore_prags if_rules
568   | ignore_prags = return []
569   | otherwise    = mapM tcIfaceRule if_rules
570
571 tcIfaceRule :: IfaceRule -> IfL CoreRule
572 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
573                         ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
574   = do  { ~(bndrs', args', rhs') <- 
575                 -- Typecheck the payload lazily, in the hope it'll never be looked at
576                 forkM (ptext (sLit "Rule") <+> ftext name) $
577                 bindIfaceBndrs bndrs                      $ \ bndrs' ->
578                 do { args' <- mapM tcIfaceExpr args
579                    ; rhs'  <- tcIfaceExpr rhs
580                    ; return (bndrs', args', rhs') }
581         ; let mb_tcs = map ifTopFreeName args
582         ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act, 
583                           ru_bndrs = bndrs', ru_args = args', 
584                           ru_rhs = rhs', 
585                           ru_rough = mb_tcs,
586                           ru_local = False }) } -- An imported RULE is never for a local Id
587                                                 -- or, even if it is (module loop, perhaps)
588                                                 -- we'll just leave it in the non-local set
589   where
590         -- This function *must* mirror exactly what Rules.topFreeName does
591         -- We could have stored the ru_rough field in the iface file
592         -- but that would be redundant, I think.
593         -- The only wrinkle is that we must not be deceived by
594         -- type syononyms at the top of a type arg.  Since
595         -- we can't tell at this point, we are careful not
596         -- to write them out in coreRuleToIfaceRule
597     ifTopFreeName :: IfaceExpr -> Maybe Name
598     ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
599     ifTopFreeName (IfaceApp f _)                    = ifTopFreeName f
600     ifTopFreeName (IfaceExt n)                      = Just n
601     ifTopFreeName _                                 = Nothing
602 \end{code}
603
604
605 %************************************************************************
606 %*                                                                      *
607                 Annotations
608 %*                                                                      *
609 %************************************************************************
610
611 \begin{code}
612 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
613 tcIfaceAnnotations = mapM tcIfaceAnnotation
614
615 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
616 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
617     target' <- tcIfaceAnnTarget target
618     return $ Annotation {
619         ann_target = target',
620         ann_value = serialized
621     }
622
623 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
624 tcIfaceAnnTarget (NamedTarget occ) = do
625     name <- lookupIfaceTop occ
626     return $ NamedTarget name
627 tcIfaceAnnTarget (ModuleTarget mod) = do
628     return $ ModuleTarget mod
629
630 \end{code}
631
632
633 %************************************************************************
634 %*                                                                      *
635                 Vectorisation information
636 %*                                                                      *
637 %************************************************************************
638
639 \begin{code}
640 tcIfaceVectInfo :: Module -> TypeEnv  -> IfaceVectInfo -> IfL VectInfo
641 tcIfaceVectInfo mod typeEnv (IfaceVectInfo 
642                              { ifaceVectInfoVar        = vars
643                              , ifaceVectInfoTyCon      = tycons
644                              , ifaceVectInfoTyConReuse = tyconsReuse
645                              })
646   = do { vVars     <- mapM vectVarMapping vars
647        ; tyConRes1 <- mapM vectTyConMapping      tycons
648        ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
649        ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
650        ; return $ VectInfo 
651                   { vectInfoVar     = mkVarEnv  vVars
652                   , vectInfoTyCon   = mkNameEnv vTyCons
653                   , vectInfoDataCon = mkNameEnv (concat vDataCons)
654                   , vectInfoPADFun  = mkNameEnv vPAs
655                   , vectInfoIso     = mkNameEnv vIsos
656                   }
657        }
658   where
659     vectVarMapping name 
660       = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
661            ; let { var  = lookupVar name
662                  ; vVar = lookupVar vName
663                  }
664            ; return (var, (var, vVar))
665            }
666     vectTyConMapping name 
667       = do { vName   <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
668            ; paName  <- lookupOrig mod (mkPADFunOcc    (nameOccName name))
669            ; isoName <- lookupOrig mod (mkVectIsoOcc   (nameOccName name))
670            ; let { tycon    = lookupTyCon name
671                  ; vTycon   = lookupTyCon vName
672                  ; paTycon  = lookupVar paName
673                  ; isoTycon = lookupVar isoName
674                  }
675            ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
676            ; return ((name, (tycon, vTycon)),    -- (T, T_v)
677                      vDataCons,                  -- list of (Ci, Ci_v)
678                      (vName, (vTycon, paTycon)), -- (T_v, paT)
679                      (name, (tycon, isoTycon)))  -- (T, isoT)
680            }
681     vectTyConReuseMapping name 
682       = do { paName  <- lookupOrig mod (mkPADFunOcc    (nameOccName name))
683            ; isoName <- lookupOrig mod (mkVectIsoOcc   (nameOccName name))
684            ; let { tycon      = lookupTyCon name
685                  ; paTycon    = lookupVar paName
686                  ; isoTycon   = lookupVar isoName
687                  ; vDataCons  = [ (dataConName dc, (dc, dc)) 
688                                 | dc <- tyConDataCons tycon]
689                  }
690            ; return ((name, (tycon, tycon)),     -- (T, T)
691                      vDataCons,                  -- list of (Ci, Ci)
692                      (name, (tycon, paTycon)),   -- (T, paT)
693                      (name, (tycon, isoTycon)))  -- (T, isoT)
694            }
695     vectDataConMapping datacon
696       = do { let name = dataConName datacon
697            ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
698            ; let vDataCon = lookupDataCon vName
699            ; return (name, (datacon, vDataCon))
700            }
701     --
702     lookupVar name = case lookupTypeEnv typeEnv name of
703                        Just (AnId var) -> var
704                        Just _         -> 
705                          panic "TcIface.tcIfaceVectInfo: not an id"
706                        Nothing        ->
707                          panic "TcIface.tcIfaceVectInfo: unknown name"
708     lookupTyCon name = case lookupTypeEnv typeEnv name of
709                          Just (ATyCon tc) -> tc
710                          Just _         -> 
711                            panic "TcIface.tcIfaceVectInfo: not a tycon"
712                          Nothing        ->
713                            panic "TcIface.tcIfaceVectInfo: unknown name"
714     lookupDataCon name = case lookupTypeEnv typeEnv name of
715                            Just (ADataCon dc) -> dc
716                            Just _         -> 
717                              panic "TcIface.tcIfaceVectInfo: not a datacon"
718                            Nothing        ->
719                              panic "TcIface.tcIfaceVectInfo: unknown name"
720 \end{code}
721
722 %************************************************************************
723 %*                                                                      *
724                         Types
725 %*                                                                      *
726 %************************************************************************
727
728 \begin{code}
729 tcIfaceType :: IfaceType -> IfL Type
730 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
731 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
732 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
733 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
734 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
735 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
736
737 tcIfaceTypes :: [IfaceType] -> IfL [Type]
738 tcIfaceTypes tys = mapM tcIfaceType tys
739
740 -----------------------------------------
741 tcIfacePredType :: IfacePredType -> IfL PredType
742 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
743 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
744 tcIfacePredType (IfaceEqPred t1 t2)  = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
745
746 -----------------------------------------
747 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
748 tcIfaceCtxt sts = mapM tcIfacePredType sts
749 \end{code}
750
751
752 %************************************************************************
753 %*                                                                      *
754                         Core
755 %*                                                                      *
756 %************************************************************************
757
758 \begin{code}
759 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
760 tcIfaceExpr (IfaceType ty)
761   = Type <$> tcIfaceType ty
762
763 tcIfaceExpr (IfaceLcl name)
764   = Var <$> tcIfaceLclId name
765
766 tcIfaceExpr (IfaceTick modName tickNo)
767   = Var <$> tcIfaceTick modName tickNo
768
769 tcIfaceExpr (IfaceExt gbl)
770   = Var <$> tcIfaceExtId gbl
771
772 tcIfaceExpr (IfaceLit lit)
773   = return (Lit lit)
774
775 tcIfaceExpr (IfaceFCall cc ty) = do
776     ty' <- tcIfaceType ty
777     u <- newUnique
778     return (Var (mkFCallId u cc ty'))
779
780 tcIfaceExpr (IfaceTuple boxity args)  = do
781     args' <- mapM tcIfaceExpr args
782     -- Put the missing type arguments back in
783     let con_args = map (Type . exprType) args' ++ args'
784     return (mkApps (Var con_id) con_args)
785   where
786     arity = length args
787     con_id = dataConWorkId (tupleCon boxity arity)
788     
789
790 tcIfaceExpr (IfaceLam bndr body)
791   = bindIfaceBndr bndr $ \bndr' ->
792     Lam bndr' <$> tcIfaceExpr body
793
794 tcIfaceExpr (IfaceApp fun arg)
795   = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
796
797 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)  = do
798     scrut' <- tcIfaceExpr scrut
799     case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
800     let
801         scrut_ty   = exprType scrut'
802         case_bndr' = mkLocalId case_bndr_name scrut_ty
803         tc_app     = splitTyConApp scrut_ty
804                 -- NB: Won't always succeed (polymoprhic case)
805                 --     but won't be demanded in those cases
806                 -- NB: not tcSplitTyConApp; we are looking at Core here
807                 --     look through non-rec newtypes to find the tycon that
808                 --     corresponds to the datacon in this case alternative
809
810     extendIfaceIdEnv [case_bndr'] $ do
811      alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
812      ty' <- tcIfaceType ty
813      return (Case scrut' case_bndr' ty' alts')
814
815 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
816     rhs' <- tcIfaceExpr rhs
817     id   <- tcIfaceLetBndr bndr
818     body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
819     return (Let (NonRec id rhs') body')
820
821 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
822     ids <- mapM tcIfaceLetBndr bndrs
823     extendIfaceIdEnv ids $ do
824      rhss' <- mapM tcIfaceExpr rhss
825      body' <- tcIfaceExpr body
826      return (Let (Rec (ids `zip` rhss')) body')
827   where
828     (bndrs, rhss) = unzip pairs
829
830 tcIfaceExpr (IfaceCast expr co) = do
831     expr' <- tcIfaceExpr expr
832     co' <- tcIfaceType co
833     return (Cast expr' co')
834
835 tcIfaceExpr (IfaceNote note expr) = do
836     expr' <- tcIfaceExpr expr
837     case note of
838         IfaceInlineMe     -> return (Note InlineMe   expr')
839         IfaceSCC cc       -> return (Note (SCC cc)   expr')
840         IfaceCoreNote n   -> return (Note (CoreNote n) expr')
841
842 -------------------------
843 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
844            -> (IfaceConAlt, [FastString], IfaceExpr)
845            -> IfL (AltCon, [TyVar], CoreExpr)
846 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
847   = ASSERT( null names ) do
848     rhs' <- tcIfaceExpr rhs
849     return (DEFAULT, [], rhs')
850   
851 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
852   = ASSERT( null names ) do
853     rhs' <- tcIfaceExpr rhs
854     return (LitAlt lit, [], rhs')
855
856 -- A case alternative is made quite a bit more complicated
857 -- by the fact that we omit type annotations because we can
858 -- work them out.  True enough, but its not that easy!
859 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
860   = do  { con <- tcIfaceDataCon data_occ
861         ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
862                (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
863         ; tcIfaceDataAlt con inst_tys arg_strs rhs }
864                   
865 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
866   = ASSERT( isTupleTyCon tycon )
867     do  { let [data_con] = tyConDataCons tycon
868         ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
869
870 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
871                -> IfL (AltCon, [TyVar], CoreExpr)
872 tcIfaceDataAlt con inst_tys arg_strs rhs
873   = do  { us <- newUniqueSupply
874         ; let uniqs = uniqsFromSupply us
875         ; let (ex_tvs, co_tvs, arg_ids)
876                       = dataConRepFSInstPat arg_strs uniqs con inst_tys
877               all_tvs = ex_tvs ++ co_tvs
878
879         ; rhs' <- extendIfaceTyVarEnv all_tvs   $
880                   extendIfaceIdEnv arg_ids      $
881                   tcIfaceExpr rhs
882         ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
883 \end{code}
884
885
886 \begin{code}
887 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind]   -- Used for external core
888 tcExtCoreBindings []     = return []
889 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
890
891 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
892 do_one (IfaceNonRec bndr rhs) thing_inside
893   = do  { rhs' <- tcIfaceExpr rhs
894         ; bndr' <- newExtCoreBndr bndr
895         ; extendIfaceIdEnv [bndr'] $ do 
896         { core_binds <- thing_inside
897         ; return (NonRec bndr' rhs' : core_binds) }}
898
899 do_one (IfaceRec pairs) thing_inside
900   = do  { bndrs' <- mapM newExtCoreBndr bndrs
901         ; extendIfaceIdEnv bndrs' $ do
902         { rhss' <- mapM tcIfaceExpr rhss
903         ; core_binds <- thing_inside
904         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
905   where
906     (bndrs,rhss) = unzip pairs
907 \end{code}
908
909
910 %************************************************************************
911 %*                                                                      *
912                 IdInfo
913 %*                                                                      *
914 %************************************************************************
915
916 \begin{code}
917 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
918 tcIdInfo ignore_prags name ty info 
919   | ignore_prags = return vanillaIdInfo
920   | otherwise    = case info of
921                         NoInfo       -> return vanillaIdInfo
922                         HasInfo info -> foldlM tcPrag init_info info
923   where
924     -- Set the CgInfo to something sensible but uninformative before
925     -- we start; default assumption is that it has CAFs
926     init_info = vanillaIdInfo
927
928     tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
929     tcPrag info HsNoCafRefs         = return (info `setCafInfo`   NoCafRefs)
930     tcPrag info (HsArity arity)     = return (info `setArityInfo` arity)
931     tcPrag info (HsStrictness str)  = return (info `setAllStrictnessInfo` Just str)
932
933         -- The next two are lazy, so they don't transitively suck stuff in
934     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
935     tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
936     tcPrag info (HsUnfold expr) = do
937           maybe_expr' <- tcPragExpr name expr
938           let
939                 -- maybe_expr' doesn't get looked at if the unfolding
940                 -- is never inspected; so the typecheck doesn't even happen
941                 unfold_info = case maybe_expr' of
942                                 Nothing    -> noUnfolding
943                                 Just expr' -> mkTopUnfolding expr' 
944           return (info `setUnfoldingInfoLazily` unfold_info)
945 \end{code}
946
947 \begin{code}
948 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
949 tcWorkerInfo ty info wkr arity
950   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
951
952         -- We return without testing maybe_wkr_id, but as soon as info is
953         -- looked at we will test it.  That's ok, because its outside the
954         -- knot; and there seems no big reason to further defer the
955         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
956         -- over the unfolding until it's actually used does seem worth while.)
957         ; us <- newUniqueSupply
958
959         ; return (case mb_wkr_id of
960                      Nothing     -> info
961                      Just wkr_id -> add_wkr_info us wkr_id info) }
962   where
963     doc = text "Worker for" <+> ppr wkr
964     add_wkr_info us wkr_id info
965         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
966                `setWorkerInfo`           HasWorker wkr_id arity
967
968     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
969
970         -- We are relying here on strictness info always appearing 
971         -- before worker info,  fingers crossed ....
972     strict_sig = case newStrictnessInfo info of
973                    Just sig -> sig
974                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr)
975 \end{code}
976
977 For unfoldings we try to do the job lazily, so that we never type check
978 an unfolding that isn't going to be looked at.
979
980 \begin{code}
981 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
982 tcPragExpr name expr
983   = forkM_maybe doc $ do
984     core_expr' <- tcIfaceExpr expr
985
986                 -- Check for type consistency in the unfolding
987     ifOptM Opt_DoCoreLinting $ do
988         in_scope <- get_in_scope_ids
989         case lintUnfolding noSrcLoc in_scope core_expr' of
990           Nothing       -> return ()
991           Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
992
993     return core_expr'
994   where
995     doc = text "Unfolding of" <+> ppr name
996     get_in_scope_ids    -- Urgh; but just for linting
997         = setLclEnv () $ 
998           do    { env <- getGblEnv 
999                 ; case if_rec_types env of {
1000                           Nothing -> return [] ;
1001                           Just (_, get_env) -> do
1002                 { type_env <- get_env
1003                 ; return (typeEnvIds type_env) }}}
1004 \end{code}
1005
1006
1007
1008 %************************************************************************
1009 %*                                                                      *
1010                 Getting from Names to TyThings
1011 %*                                                                      *
1012 %************************************************************************
1013
1014 \begin{code}
1015 tcIfaceGlobal :: Name -> IfL TyThing
1016 tcIfaceGlobal name
1017   | Just thing <- wiredInNameTyThing_maybe name
1018         -- Wired-in things include TyCons, DataCons, and Ids
1019   = do { ifCheckWiredInThing name; return thing }
1020   | otherwise
1021   = do  { env <- getGblEnv
1022         ; case if_rec_types env of {    -- Note [Tying the knot]
1023             Just (mod, get_type_env) 
1024                 | nameIsLocalOrFrom mod name
1025                 -> do           -- It's defined in the module being compiled
1026                 { type_env <- setLclEnv () get_type_env         -- yuk
1027                 ; case lookupNameEnv type_env name of
1028                         Just thing -> return thing
1029                         Nothing   -> pprPanic "tcIfaceGlobal (local): not found:"  
1030                                                 (ppr name $$ ppr type_env) }
1031
1032           ; _ -> do
1033
1034         { hsc_env <- getTopEnv
1035         ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1036         ; case mb_thing of {
1037             Just thing -> return thing ;
1038             Nothing    -> do
1039
1040         { mb_thing <- importDecl name   -- It's imported; go get it
1041         ; case mb_thing of
1042             Failed err      -> failIfM err
1043             Succeeded thing -> return thing
1044     }}}}}
1045
1046 -- Note [Tying the knot]
1047 -- ~~~~~~~~~~~~~~~~~~~~~
1048 -- The if_rec_types field is used in two situations:
1049 --
1050 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1051 --    Then we look up M.T in M's type environment, which is splatted into if_rec_types
1052 --    after we've built M's type envt.
1053 --
1054 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1055 --    is up to date.  So we call typecheckIface on M.hi.  This splats M.T into 
1056 --    if_rec_types so that the (lazily typechecked) decls see all the other decls
1057 --
1058 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1059 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1060 -- emasculated form (e.g. lacking data constructors).
1061
1062 ifCheckWiredInThing :: Name -> IfL ()
1063 -- Even though we are in an interface file, we want to make
1064 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1065 -- Ditto want to ensure that RULES are loaded too
1066 -- See Note [Loading instances] in LoadIface
1067 ifCheckWiredInThing name 
1068   = do  { mod <- getIfModule
1069                 -- Check whether we are typechecking the interface for this
1070                 -- very module.  E.g when compiling the base library in --make mode
1071                 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1072                 -- the HPT, so without the test we'll demand-load it into the PIT!
1073                 -- C.f. the same test in checkWiredInTyCon above
1074         ; ASSERT2( isExternalName name, ppr name ) 
1075           unless (mod == nameModule name)
1076                  (loadWiredInHomeIface name) }
1077
1078 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1079 tcIfaceTyCon IfaceIntTc         = tcWiredInTyCon intTyCon
1080 tcIfaceTyCon IfaceBoolTc        = tcWiredInTyCon boolTyCon
1081 tcIfaceTyCon IfaceCharTc        = tcWiredInTyCon charTyCon
1082 tcIfaceTyCon IfaceListTc        = tcWiredInTyCon listTyCon
1083 tcIfaceTyCon IfacePArrTc        = tcWiredInTyCon parrTyCon
1084 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1085 tcIfaceTyCon (IfaceTc name)     = do { thing <- tcIfaceGlobal name 
1086                                      ; return (check_tc (tyThingTyCon thing)) }
1087   where
1088     check_tc tc
1089      | debugIsOn = case toIfaceTyCon tc of
1090                    IfaceTc _ -> tc
1091                    _         -> pprTrace "check_tc" (ppr tc) tc
1092      | otherwise = tc
1093 -- we should be okay just returning Kind constructors without extra loading
1094 tcIfaceTyCon IfaceLiftedTypeKindTc   = return liftedTypeKindTyCon
1095 tcIfaceTyCon IfaceOpenTypeKindTc     = return openTypeKindTyCon
1096 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1097 tcIfaceTyCon IfaceArgTypeKindTc      = return argTypeKindTyCon
1098 tcIfaceTyCon IfaceUbxTupleKindTc     = return ubxTupleKindTyCon
1099
1100 -- Even though we are in an interface file, we want to make
1101 -- sure the instances and RULES of this tycon are loaded 
1102 -- Imagine: f :: Double -> Double
1103 tcWiredInTyCon :: TyCon -> IfL TyCon
1104 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1105                        ; return tc }
1106
1107 tcIfaceClass :: Name -> IfL Class
1108 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1109                        ; return (tyThingClass thing) }
1110
1111 tcIfaceDataCon :: Name -> IfL DataCon
1112 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1113                          ; case thing of
1114                                 ADataCon dc -> return dc
1115                                 _       -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1116
1117 tcIfaceExtId :: Name -> IfL Id
1118 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1119                        ; case thing of
1120                           AnId id -> return id
1121                           _       -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1122 \end{code}
1123
1124 %************************************************************************
1125 %*                                                                      *
1126                 Bindings
1127 %*                                                                      *
1128 %************************************************************************
1129
1130 \begin{code}
1131 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1132 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1133   = do  { name <- newIfaceName (mkVarOccFS fs)
1134         ; ty' <- tcIfaceType ty
1135         ; let id = mkLocalId name ty'
1136         ; extendIfaceIdEnv [id] (thing_inside id) }
1137 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1138   = bindIfaceTyVar bndr thing_inside
1139     
1140 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1141 bindIfaceBndrs []     thing_inside = thing_inside []
1142 bindIfaceBndrs (b:bs) thing_inside
1143   = bindIfaceBndr b     $ \ b' ->
1144     bindIfaceBndrs bs   $ \ bs' ->
1145     thing_inside (b':bs')
1146
1147 -----------------------
1148 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1149 tcIfaceLetBndr (IfLetBndr fs ty info)
1150   = do  { name <- newIfaceName (mkVarOccFS fs)
1151         ; ty' <- tcIfaceType ty
1152         ; case info of
1153                 NoInfo    -> return (mkLocalId name ty')
1154                 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) } 
1155   where
1156         -- Similar to tcIdInfo, but much simpler
1157     tc_info [] = vanillaIdInfo
1158     tc_info (HsInline p     : i) = tc_info i `setInlinePragInfo` p 
1159     tc_info (HsArity a      : i) = tc_info i `setArityInfo` a 
1160     tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s 
1161     tc_info (other          : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo" 
1162                                             (ppr other) (tc_info i)
1163
1164 -----------------------
1165 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1166 newExtCoreBndr (IfLetBndr var ty _)    -- Ignoring IdInfo for now
1167   = do  { mod <- getIfModule
1168         ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1169         ; ty' <- tcIfaceType ty
1170         ; return (mkLocalId name ty') }
1171
1172 -----------------------
1173 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1174 bindIfaceTyVar (occ,kind) thing_inside
1175   = do  { name <- newIfaceName (mkTyVarOccFS occ)
1176         ; tyvar <- mk_iface_tyvar name kind
1177         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1178
1179 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1180 bindIfaceTyVars bndrs thing_inside
1181   = do  { names <- newIfaceNames (map mkTyVarOccFS occs)
1182         ; tyvars <- zipWithM mk_iface_tyvar names kinds
1183         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1184   where
1185     (occs,kinds) = unzip bndrs
1186
1187 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1188 mk_iface_tyvar name ifKind
1189    = do { kind <- tcIfaceType ifKind
1190         ; if isCoercionKind kind then 
1191                 return (Var.mkCoVar name kind)
1192           else
1193                 return (Var.mkTyVar name kind) }
1194 \end{code}
1195