Rollback INLINE patches
[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 = zipWith setTyThingPoss ats' (map ifTyVars rdr_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    -- For each AT argument compute the position of the corresponding class
449    -- parameter in the class head.  This will later serve as a permutation
450    -- vector when checking the validity of instance declarations.
451    setTyThingPoss (ATyCon tycon) atTyVars = 
452      let classTyVars = map fst tv_bndrs
453          poss        =   catMaybes 
454                        . map ((`elemIndex` classTyVars) . fst) 
455                        $ atTyVars
456                     -- There will be no Nothing, as we already passed renaming
457      in 
458      ATyCon (setTyConArgPoss tycon poss)
459    setTyThingPoss _               _ = panic "TcIface.setTyThingPoss"
460
461 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
462   = do  { name <- lookupIfaceTop rdr_name
463         ; return (ATyCon (mkForeignTyCon name ext_name 
464                                          liftedTypeKind 0)) }
465
466 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
467 tcIfaceDataCons tycon_name tycon _ if_cons
468   = case if_cons of
469         IfAbstractTyCon  -> return mkAbstractTyConRhs
470         IfOpenDataTyCon  -> return mkOpenDataTyConRhs
471         IfDataTyCon cons -> do  { data_cons <- mapM tc_con_decl cons
472                                 ; return (mkDataTyConRhs data_cons) }
473         IfNewTyCon con   -> do  { data_con <- tc_con_decl con
474                                 ; mkNewTyConRhs tycon_name tycon data_con }
475   where
476     tc_con_decl (IfCon { ifConInfix = is_infix, 
477                          ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
478                          ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
479                          ifConArgTys = args, ifConFields = field_lbls,
480                          ifConStricts = stricts})
481      = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
482        bindIfaceTyVars ex_tvs    $ \ ex_tyvars -> do
483         { name  <- lookupIfaceTop occ
484         ; eq_spec <- tcIfaceEqSpec spec
485         ; theta <- tcIfaceCtxt ctxt     -- Laziness seems not worth the bother here
486                 -- At one stage I thought that this context checking *had*
487                 -- to be lazy, because of possible mutual recursion between the
488                 -- type and the classe: 
489                 -- E.g. 
490                 --      class Real a where { toRat :: a -> Ratio Integer }
491                 --      data (Real a) => Ratio a = ...
492                 -- But now I think that the laziness in checking class ops breaks 
493                 -- the loop, so no laziness needed
494
495         -- Read the argument types, but lazily to avoid faulting in
496         -- the component types unless they are really needed
497         ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
498         ; lbl_names <- mapM lookupIfaceTop field_lbls
499
500         -- Remember, tycon is the representation tycon
501         ; let orig_res_ty = mkFamilyTyConApp tycon 
502                                 (substTyVars (mkTopTvSubst eq_spec) univ_tyvars)
503
504         ; buildDataCon name is_infix {- Not infix -}
505                        stricts lbl_names
506                        univ_tyvars ex_tyvars 
507                        eq_spec theta 
508                        arg_tys orig_res_ty tycon
509         }
510     mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
511
512 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
513 tcIfaceEqSpec spec
514   = mapM do_item spec
515   where
516     do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
517                               ; ty <- tcIfaceType if_ty
518                               ; return (tv,ty) }
519 \end{code}
520
521 Note [Synonym kind loop]
522 ~~~~~~~~~~~~~~~~~~~~~~~~
523 Notice that we eagerly grab the *kind* from the interface file, but
524 build a forkM thunk for the *rhs* (and family stuff).  To see why, 
525 consider this (Trac #2412)
526
527 M.hs:       module M where { import X; data T = MkT S }
528 X.hs:       module X where { import {-# SOURCE #-} M; type S = T }
529 M.hs-boot:  module M where { data T }
530
531 When kind-checking M.hs we need S's kind.  But we do not want to
532 find S's kind from (typeKind S-rhs), because we don't want to look at
533 S-rhs yet!  Since S is imported from X.hi, S gets just one chance to
534 be defined, and we must not do that until we've finished with M.T.
535
536 Solution: record S's kind in the interface file; now we can safely
537 look at it.
538
539 %************************************************************************
540 %*                                                                      *
541                 Instances
542 %*                                                                      *
543 %************************************************************************
544
545 \begin{code}
546 tcIfaceInst :: IfaceInst -> IfL Instance
547 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
548                          ifInstCls = cls, ifInstTys = mb_tcs })
549   = do  { dfun    <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
550                      tcIfaceExtId dfun_occ
551         ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
552         ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
553
554 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
555 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon, 
556                                ifFamInstFam = fam, ifFamInstTys = mb_tcs })
557 --      { tycon'  <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
558 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
559     = do tycon'  <- forkM (text ("Inst tycon") <+> ppr tycon) $
560                     tcIfaceTyCon tycon
561          let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
562          return (mkImportedFamInst fam mb_tcs' tycon')
563 \end{code}
564
565
566 %************************************************************************
567 %*                                                                      *
568                 Rules
569 %*                                                                      *
570 %************************************************************************
571
572 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
573 are in the type environment.  However, remember that typechecking a Rule may 
574 (as a side effect) augment the type envt, and so we may need to iterate the process.
575
576 \begin{code}
577 tcIfaceRules :: Bool            -- True <=> ignore rules
578              -> [IfaceRule]
579              -> IfL [CoreRule]
580 tcIfaceRules ignore_prags if_rules
581   | ignore_prags = return []
582   | otherwise    = mapM tcIfaceRule if_rules
583
584 tcIfaceRule :: IfaceRule -> IfL CoreRule
585 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
586                         ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
587   = do  { ~(bndrs', args', rhs') <- 
588                 -- Typecheck the payload lazily, in the hope it'll never be looked at
589                 forkM (ptext (sLit "Rule") <+> ftext name) $
590                 bindIfaceBndrs bndrs                      $ \ bndrs' ->
591                 do { args' <- mapM tcIfaceExpr args
592                    ; rhs'  <- tcIfaceExpr rhs
593                    ; return (bndrs', args', rhs') }
594         ; let mb_tcs = map ifTopFreeName args
595         ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act, 
596                           ru_bndrs = bndrs', ru_args = args', 
597                           ru_rhs = rhs', 
598                           ru_rough = mb_tcs,
599                           ru_local = False }) } -- An imported RULE is never for a local Id
600                                                 -- or, even if it is (module loop, perhaps)
601                                                 -- we'll just leave it in the non-local set
602   where
603         -- This function *must* mirror exactly what Rules.topFreeName does
604         -- We could have stored the ru_rough field in the iface file
605         -- but that would be redundant, I think.
606         -- The only wrinkle is that we must not be deceived by
607         -- type syononyms at the top of a type arg.  Since
608         -- we can't tell at this point, we are careful not
609         -- to write them out in coreRuleToIfaceRule
610     ifTopFreeName :: IfaceExpr -> Maybe Name
611     ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
612     ifTopFreeName (IfaceApp f _)                    = ifTopFreeName f
613     ifTopFreeName (IfaceExt n)                      = Just n
614     ifTopFreeName _                                 = Nothing
615 \end{code}
616
617
618 %************************************************************************
619 %*                                                                      *
620                 Annotations
621 %*                                                                      *
622 %************************************************************************
623
624 \begin{code}
625 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
626 tcIfaceAnnotations = mapM tcIfaceAnnotation
627
628 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
629 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
630     target' <- tcIfaceAnnTarget target
631     return $ Annotation {
632         ann_target = target',
633         ann_value = serialized
634     }
635
636 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
637 tcIfaceAnnTarget (NamedTarget occ) = do
638     name <- lookupIfaceTop occ
639     return $ NamedTarget name
640 tcIfaceAnnTarget (ModuleTarget mod) = do
641     return $ ModuleTarget mod
642
643 \end{code}
644
645
646 %************************************************************************
647 %*                                                                      *
648                 Vectorisation information
649 %*                                                                      *
650 %************************************************************************
651
652 \begin{code}
653 tcIfaceVectInfo :: Module -> TypeEnv  -> IfaceVectInfo -> IfL VectInfo
654 tcIfaceVectInfo mod typeEnv (IfaceVectInfo 
655                              { ifaceVectInfoVar        = vars
656                              , ifaceVectInfoTyCon      = tycons
657                              , ifaceVectInfoTyConReuse = tyconsReuse
658                              })
659   = do { vVars     <- mapM vectVarMapping vars
660        ; tyConRes1 <- mapM vectTyConMapping      tycons
661        ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
662        ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
663        ; return $ VectInfo 
664                   { vectInfoVar     = mkVarEnv  vVars
665                   , vectInfoTyCon   = mkNameEnv vTyCons
666                   , vectInfoDataCon = mkNameEnv (concat vDataCons)
667                   , vectInfoPADFun  = mkNameEnv vPAs
668                   , vectInfoIso     = mkNameEnv vIsos
669                   }
670        }
671   where
672     vectVarMapping name 
673       = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
674            ; let { var  = lookupVar name
675                  ; vVar = lookupVar vName
676                  }
677            ; return (var, (var, vVar))
678            }
679     vectTyConMapping name 
680       = do { vName   <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
681            ; paName  <- lookupOrig mod (mkPADFunOcc    (nameOccName name))
682            ; isoName <- lookupOrig mod (mkVectIsoOcc   (nameOccName name))
683            ; let { tycon    = lookupTyCon name
684                  ; vTycon   = lookupTyCon vName
685                  ; paTycon  = lookupVar paName
686                  ; isoTycon = lookupVar isoName
687                  }
688            ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
689            ; return ((name, (tycon, vTycon)),    -- (T, T_v)
690                      vDataCons,                  -- list of (Ci, Ci_v)
691                      (vName, (vTycon, paTycon)), -- (T_v, paT)
692                      (name, (tycon, isoTycon)))  -- (T, isoT)
693            }
694     vectTyConReuseMapping name 
695       = do { paName  <- lookupOrig mod (mkPADFunOcc    (nameOccName name))
696            ; isoName <- lookupOrig mod (mkVectIsoOcc   (nameOccName name))
697            ; let { tycon      = lookupTyCon name
698                  ; paTycon    = lookupVar paName
699                  ; isoTycon   = lookupVar isoName
700                  ; vDataCons  = [ (dataConName dc, (dc, dc)) 
701                                 | dc <- tyConDataCons tycon]
702                  }
703            ; return ((name, (tycon, tycon)),     -- (T, T)
704                      vDataCons,                  -- list of (Ci, Ci)
705                      (name, (tycon, paTycon)),   -- (T, paT)
706                      (name, (tycon, isoTycon)))  -- (T, isoT)
707            }
708     vectDataConMapping datacon
709       = do { let name = dataConName datacon
710            ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
711            ; let vDataCon = lookupDataCon vName
712            ; return (name, (datacon, vDataCon))
713            }
714     --
715     lookupVar name = case lookupTypeEnv typeEnv name of
716                        Just (AnId var) -> var
717                        Just _         -> 
718                          panic "TcIface.tcIfaceVectInfo: not an id"
719                        Nothing        ->
720                          panic "TcIface.tcIfaceVectInfo: unknown name"
721     lookupTyCon name = case lookupTypeEnv typeEnv name of
722                          Just (ATyCon tc) -> tc
723                          Just _         -> 
724                            panic "TcIface.tcIfaceVectInfo: not a tycon"
725                          Nothing        ->
726                            panic "TcIface.tcIfaceVectInfo: unknown name"
727     lookupDataCon name = case lookupTypeEnv typeEnv name of
728                            Just (ADataCon dc) -> dc
729                            Just _         -> 
730                              panic "TcIface.tcIfaceVectInfo: not a datacon"
731                            Nothing        ->
732                              panic "TcIface.tcIfaceVectInfo: unknown name"
733 \end{code}
734
735 %************************************************************************
736 %*                                                                      *
737                         Types
738 %*                                                                      *
739 %************************************************************************
740
741 \begin{code}
742 tcIfaceType :: IfaceType -> IfL Type
743 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
744 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
745 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
746 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
747 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
748 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
749
750 tcIfaceTypes :: [IfaceType] -> IfL [Type]
751 tcIfaceTypes tys = mapM tcIfaceType tys
752
753 -----------------------------------------
754 tcIfacePredType :: IfacePredType -> IfL PredType
755 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
756 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
757 tcIfacePredType (IfaceEqPred t1 t2)  = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
758
759 -----------------------------------------
760 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
761 tcIfaceCtxt sts = mapM tcIfacePredType sts
762 \end{code}
763
764
765 %************************************************************************
766 %*                                                                      *
767                         Core
768 %*                                                                      *
769 %************************************************************************
770
771 \begin{code}
772 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
773 tcIfaceExpr (IfaceType ty)
774   = Type <$> tcIfaceType ty
775
776 tcIfaceExpr (IfaceLcl name)
777   = Var <$> tcIfaceLclId name
778
779 tcIfaceExpr (IfaceTick modName tickNo)
780   = Var <$> tcIfaceTick modName tickNo
781
782 tcIfaceExpr (IfaceExt gbl)
783   = Var <$> tcIfaceExtId gbl
784
785 tcIfaceExpr (IfaceLit lit)
786   = return (Lit lit)
787
788 tcIfaceExpr (IfaceFCall cc ty) = do
789     ty' <- tcIfaceType ty
790     u <- newUnique
791     return (Var (mkFCallId u cc ty'))
792
793 tcIfaceExpr (IfaceTuple boxity args)  = do
794     args' <- mapM tcIfaceExpr args
795     -- Put the missing type arguments back in
796     let con_args = map (Type . exprType) args' ++ args'
797     return (mkApps (Var con_id) con_args)
798   where
799     arity = length args
800     con_id = dataConWorkId (tupleCon boxity arity)
801     
802
803 tcIfaceExpr (IfaceLam bndr body)
804   = bindIfaceBndr bndr $ \bndr' ->
805     Lam bndr' <$> tcIfaceExpr body
806
807 tcIfaceExpr (IfaceApp fun arg)
808   = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
809
810 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)  = do
811     scrut' <- tcIfaceExpr scrut
812     case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
813     let
814         scrut_ty   = exprType scrut'
815         case_bndr' = mkLocalId case_bndr_name scrut_ty
816         tc_app     = splitTyConApp scrut_ty
817                 -- NB: Won't always succeed (polymoprhic case)
818                 --     but won't be demanded in those cases
819                 -- NB: not tcSplitTyConApp; we are looking at Core here
820                 --     look through non-rec newtypes to find the tycon that
821                 --     corresponds to the datacon in this case alternative
822
823     extendIfaceIdEnv [case_bndr'] $ do
824      alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
825      ty' <- tcIfaceType ty
826      return (Case scrut' case_bndr' ty' alts')
827
828 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
829     rhs' <- tcIfaceExpr rhs
830     id   <- tcIfaceLetBndr bndr
831     body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
832     return (Let (NonRec id rhs') body')
833
834 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
835     ids <- mapM tcIfaceLetBndr bndrs
836     extendIfaceIdEnv ids $ do
837      rhss' <- mapM tcIfaceExpr rhss
838      body' <- tcIfaceExpr body
839      return (Let (Rec (ids `zip` rhss')) body')
840   where
841     (bndrs, rhss) = unzip pairs
842
843 tcIfaceExpr (IfaceCast expr co) = do
844     expr' <- tcIfaceExpr expr
845     co' <- tcIfaceType co
846     return (Cast expr' co')
847
848 tcIfaceExpr (IfaceNote note expr) = do
849     expr' <- tcIfaceExpr expr
850     case note of
851         IfaceInlineMe     -> return (Note InlineMe   expr')
852         IfaceSCC cc       -> return (Note (SCC cc)   expr')
853         IfaceCoreNote n   -> return (Note (CoreNote n) expr')
854
855 -------------------------
856 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
857            -> (IfaceConAlt, [FastString], IfaceExpr)
858            -> IfL (AltCon, [TyVar], CoreExpr)
859 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
860   = ASSERT( null names ) do
861     rhs' <- tcIfaceExpr rhs
862     return (DEFAULT, [], rhs')
863   
864 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
865   = ASSERT( null names ) do
866     rhs' <- tcIfaceExpr rhs
867     return (LitAlt lit, [], rhs')
868
869 -- A case alternative is made quite a bit more complicated
870 -- by the fact that we omit type annotations because we can
871 -- work them out.  True enough, but its not that easy!
872 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
873   = do  { con <- tcIfaceDataCon data_occ
874         ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
875                (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
876         ; tcIfaceDataAlt con inst_tys arg_strs rhs }
877                   
878 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
879   = ASSERT( isTupleTyCon tycon )
880     do  { let [data_con] = tyConDataCons tycon
881         ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
882
883 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
884                -> IfL (AltCon, [TyVar], CoreExpr)
885 tcIfaceDataAlt con inst_tys arg_strs rhs
886   = do  { us <- newUniqueSupply
887         ; let uniqs = uniqsFromSupply us
888         ; let (ex_tvs, co_tvs, arg_ids)
889                       = dataConRepFSInstPat arg_strs uniqs con inst_tys
890               all_tvs = ex_tvs ++ co_tvs
891
892         ; rhs' <- extendIfaceTyVarEnv all_tvs   $
893                   extendIfaceIdEnv arg_ids      $
894                   tcIfaceExpr rhs
895         ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
896 \end{code}
897
898
899 \begin{code}
900 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind]   -- Used for external core
901 tcExtCoreBindings []     = return []
902 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
903
904 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
905 do_one (IfaceNonRec bndr rhs) thing_inside
906   = do  { rhs' <- tcIfaceExpr rhs
907         ; bndr' <- newExtCoreBndr bndr
908         ; extendIfaceIdEnv [bndr'] $ do 
909         { core_binds <- thing_inside
910         ; return (NonRec bndr' rhs' : core_binds) }}
911
912 do_one (IfaceRec pairs) thing_inside
913   = do  { bndrs' <- mapM newExtCoreBndr bndrs
914         ; extendIfaceIdEnv bndrs' $ do
915         { rhss' <- mapM tcIfaceExpr rhss
916         ; core_binds <- thing_inside
917         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
918   where
919     (bndrs,rhss) = unzip pairs
920 \end{code}
921
922
923 %************************************************************************
924 %*                                                                      *
925                 IdInfo
926 %*                                                                      *
927 %************************************************************************
928
929 \begin{code}
930 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
931 tcIdInfo ignore_prags name ty info 
932   | ignore_prags = return vanillaIdInfo
933   | otherwise    = case info of
934                         NoInfo       -> return vanillaIdInfo
935                         HasInfo info -> foldlM tcPrag init_info info
936   where
937     -- Set the CgInfo to something sensible but uninformative before
938     -- we start; default assumption is that it has CAFs
939     init_info = vanillaIdInfo
940
941     tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
942     tcPrag info HsNoCafRefs         = return (info `setCafInfo`   NoCafRefs)
943     tcPrag info (HsArity arity)     = return (info `setArityInfo` arity)
944     tcPrag info (HsStrictness str)  = return (info `setAllStrictnessInfo` Just str)
945
946         -- The next two are lazy, so they don't transitively suck stuff in
947     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
948     tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
949     tcPrag info (HsUnfold expr) = do
950           maybe_expr' <- tcPragExpr name expr
951           let
952                 -- maybe_expr' doesn't get looked at if the unfolding
953                 -- is never inspected; so the typecheck doesn't even happen
954                 unfold_info = case maybe_expr' of
955                                 Nothing    -> noUnfolding
956                                 Just expr' -> mkTopUnfolding expr' 
957           return (info `setUnfoldingInfoLazily` unfold_info)
958 \end{code}
959
960 \begin{code}
961 tcWorkerInfo :: Type -> IdInfo -> Name -> Arity -> IfL IdInfo
962 tcWorkerInfo ty info wkr arity
963   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
964
965         -- We return without testing maybe_wkr_id, but as soon as info is
966         -- looked at we will test it.  That's ok, because its outside the
967         -- knot; and there seems no big reason to further defer the
968         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
969         -- over the unfolding until it's actually used does seem worth while.)
970         ; us <- newUniqueSupply
971
972         ; return (case mb_wkr_id of
973                      Nothing     -> info
974                      Just wkr_id -> add_wkr_info us wkr_id info) }
975   where
976     doc = text "Worker for" <+> ppr wkr
977     add_wkr_info us wkr_id info
978         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
979                `setWorkerInfo`           HasWorker wkr_id arity
980
981     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
982
983         -- We are relying here on strictness info always appearing 
984         -- before worker info,  fingers crossed ....
985     strict_sig = case newStrictnessInfo info of
986                    Just sig -> sig
987                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr)
988 \end{code}
989
990 For unfoldings we try to do the job lazily, so that we never type check
991 an unfolding that isn't going to be looked at.
992
993 \begin{code}
994 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
995 tcPragExpr name expr
996   = forkM_maybe doc $ do
997     core_expr' <- tcIfaceExpr expr
998
999                 -- Check for type consistency in the unfolding
1000     ifOptM Opt_DoCoreLinting $ do
1001         in_scope <- get_in_scope_ids
1002         case lintUnfolding noSrcLoc in_scope core_expr' of
1003           Nothing       -> return ()
1004           Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
1005
1006     return core_expr'
1007   where
1008     doc = text "Unfolding of" <+> ppr name
1009     get_in_scope_ids    -- Urgh; but just for linting
1010         = setLclEnv () $ 
1011           do    { env <- getGblEnv 
1012                 ; case if_rec_types env of {
1013                           Nothing -> return [] ;
1014                           Just (_, get_env) -> do
1015                 { type_env <- get_env
1016                 ; return (typeEnvIds type_env) }}}
1017 \end{code}
1018
1019
1020
1021 %************************************************************************
1022 %*                                                                      *
1023                 Getting from Names to TyThings
1024 %*                                                                      *
1025 %************************************************************************
1026
1027 \begin{code}
1028 tcIfaceGlobal :: Name -> IfL TyThing
1029 tcIfaceGlobal name
1030   | Just thing <- wiredInNameTyThing_maybe name
1031         -- Wired-in things include TyCons, DataCons, and Ids
1032   = do { ifCheckWiredInThing name; return thing }
1033   | otherwise
1034   = do  { env <- getGblEnv
1035         ; case if_rec_types env of {    -- Note [Tying the knot]
1036             Just (mod, get_type_env) 
1037                 | nameIsLocalOrFrom mod name
1038                 -> do           -- It's defined in the module being compiled
1039                 { type_env <- setLclEnv () get_type_env         -- yuk
1040                 ; case lookupNameEnv type_env name of
1041                         Just thing -> return thing
1042                         Nothing   -> pprPanic "tcIfaceGlobal (local): not found:"  
1043                                                 (ppr name $$ ppr type_env) }
1044
1045           ; _ -> do
1046
1047         { hsc_env <- getTopEnv
1048         ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1049         ; case mb_thing of {
1050             Just thing -> return thing ;
1051             Nothing    -> do
1052
1053         { mb_thing <- importDecl name   -- It's imported; go get it
1054         ; case mb_thing of
1055             Failed err      -> failIfM err
1056             Succeeded thing -> return thing
1057     }}}}}
1058
1059 -- Note [Tying the knot]
1060 -- ~~~~~~~~~~~~~~~~~~~~~
1061 -- The if_rec_types field is used in two situations:
1062 --
1063 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1064 --    Then we look up M.T in M's type environment, which is splatted into if_rec_types
1065 --    after we've built M's type envt.
1066 --
1067 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1068 --    is up to date.  So we call typecheckIface on M.hi.  This splats M.T into 
1069 --    if_rec_types so that the (lazily typechecked) decls see all the other decls
1070 --
1071 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1072 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1073 -- emasculated form (e.g. lacking data constructors).
1074
1075 ifCheckWiredInThing :: Name -> IfL ()
1076 -- Even though we are in an interface file, we want to make
1077 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1078 -- Ditto want to ensure that RULES are loaded too
1079 -- See Note [Loading instances] in LoadIface
1080 ifCheckWiredInThing name 
1081   = do  { mod <- getIfModule
1082                 -- Check whether we are typechecking the interface for this
1083                 -- very module.  E.g when compiling the base library in --make mode
1084                 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1085                 -- the HPT, so without the test we'll demand-load it into the PIT!
1086                 -- C.f. the same test in checkWiredInTyCon above
1087         ; ASSERT2( isExternalName name, ppr name ) 
1088           unless (mod == nameModule name)
1089                  (loadWiredInHomeIface name) }
1090
1091 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1092 tcIfaceTyCon IfaceIntTc         = tcWiredInTyCon intTyCon
1093 tcIfaceTyCon IfaceBoolTc        = tcWiredInTyCon boolTyCon
1094 tcIfaceTyCon IfaceCharTc        = tcWiredInTyCon charTyCon
1095 tcIfaceTyCon IfaceListTc        = tcWiredInTyCon listTyCon
1096 tcIfaceTyCon IfacePArrTc        = tcWiredInTyCon parrTyCon
1097 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1098 tcIfaceTyCon (IfaceTc name)     = do { thing <- tcIfaceGlobal name 
1099                                      ; return (check_tc (tyThingTyCon thing)) }
1100   where
1101     check_tc tc
1102      | debugIsOn = case toIfaceTyCon tc of
1103                    IfaceTc _ -> tc
1104                    _         -> pprTrace "check_tc" (ppr tc) tc
1105      | otherwise = tc
1106 -- we should be okay just returning Kind constructors without extra loading
1107 tcIfaceTyCon IfaceLiftedTypeKindTc   = return liftedTypeKindTyCon
1108 tcIfaceTyCon IfaceOpenTypeKindTc     = return openTypeKindTyCon
1109 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1110 tcIfaceTyCon IfaceArgTypeKindTc      = return argTypeKindTyCon
1111 tcIfaceTyCon IfaceUbxTupleKindTc     = return ubxTupleKindTyCon
1112
1113 -- Even though we are in an interface file, we want to make
1114 -- sure the instances and RULES of this tycon are loaded 
1115 -- Imagine: f :: Double -> Double
1116 tcWiredInTyCon :: TyCon -> IfL TyCon
1117 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1118                        ; return tc }
1119
1120 tcIfaceClass :: Name -> IfL Class
1121 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1122                        ; return (tyThingClass thing) }
1123
1124 tcIfaceDataCon :: Name -> IfL DataCon
1125 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1126                          ; case thing of
1127                                 ADataCon dc -> return dc
1128                                 _       -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1129
1130 tcIfaceExtId :: Name -> IfL Id
1131 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1132                        ; case thing of
1133                           AnId id -> return id
1134                           _       -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1135 \end{code}
1136
1137 %************************************************************************
1138 %*                                                                      *
1139                 Bindings
1140 %*                                                                      *
1141 %************************************************************************
1142
1143 \begin{code}
1144 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1145 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1146   = do  { name <- newIfaceName (mkVarOccFS fs)
1147         ; ty' <- tcIfaceType ty
1148         ; let id = mkLocalId name ty'
1149         ; extendIfaceIdEnv [id] (thing_inside id) }
1150 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1151   = bindIfaceTyVar bndr thing_inside
1152     
1153 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1154 bindIfaceBndrs []     thing_inside = thing_inside []
1155 bindIfaceBndrs (b:bs) thing_inside
1156   = bindIfaceBndr b     $ \ b' ->
1157     bindIfaceBndrs bs   $ \ bs' ->
1158     thing_inside (b':bs')
1159
1160 -----------------------
1161 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1162 tcIfaceLetBndr (IfLetBndr fs ty info)
1163   = do  { name <- newIfaceName (mkVarOccFS fs)
1164         ; ty' <- tcIfaceType ty
1165         ; case info of
1166                 NoInfo    -> return (mkLocalId name ty')
1167                 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) } 
1168   where
1169         -- Similar to tcIdInfo, but much simpler
1170     tc_info [] = vanillaIdInfo
1171     tc_info (HsInline p     : i) = tc_info i `setInlinePragInfo` p 
1172     tc_info (HsArity a      : i) = tc_info i `setArityInfo` a 
1173     tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s 
1174     tc_info (other          : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo" 
1175                                             (ppr other) (tc_info i)
1176
1177 -----------------------
1178 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1179 newExtCoreBndr (IfLetBndr var ty _)    -- Ignoring IdInfo for now
1180   = do  { mod <- getIfModule
1181         ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1182         ; ty' <- tcIfaceType ty
1183         ; return (mkLocalId name ty') }
1184
1185 -----------------------
1186 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1187 bindIfaceTyVar (occ,kind) thing_inside
1188   = do  { name <- newIfaceName (mkTyVarOccFS occ)
1189         ; tyvar <- mk_iface_tyvar name kind
1190         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1191
1192 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1193 bindIfaceTyVars bndrs thing_inside
1194   = do  { names <- newIfaceNames (map mkTyVarOccFS occs)
1195         ; tyvars <- zipWithM mk_iface_tyvar names kinds
1196         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1197   where
1198     (occs,kinds) = unzip bndrs
1199
1200 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1201 mk_iface_tyvar name ifKind
1202    = do { kind <- tcIfaceType ifKind
1203         ; if isCoercionKind kind then 
1204                 return (Var.mkCoVar name kind)
1205           else
1206                 return (Var.mkTyVar name kind) }
1207 \end{code}
1208