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