DEBUG removal
[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         ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
818                (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
819         ; tcIfaceDataAlt con inst_tys arg_strs rhs }
820                   
821 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
822   = ASSERT( isTupleTyCon tycon )
823     do  { let [data_con] = tyConDataCons tycon
824         ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
825
826 tcIfaceDataAlt con inst_tys arg_strs rhs
827   = do  { us <- newUniqueSupply
828         ; let uniqs = uniqsFromSupply us
829         ; let (ex_tvs, co_tvs, arg_ids)
830                       = dataConRepFSInstPat arg_strs uniqs con inst_tys
831               all_tvs = ex_tvs ++ co_tvs
832
833         ; rhs' <- extendIfaceTyVarEnv all_tvs   $
834                   extendIfaceIdEnv arg_ids      $
835                   tcIfaceExpr rhs
836         ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
837 \end{code}
838
839
840 \begin{code}
841 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind]   -- Used for external core
842 tcExtCoreBindings []     = return []
843 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
844
845 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
846 do_one (IfaceNonRec bndr rhs) thing_inside
847   = do  { rhs' <- tcIfaceExpr rhs
848         ; bndr' <- newExtCoreBndr bndr
849         ; extendIfaceIdEnv [bndr'] $ do 
850         { core_binds <- thing_inside
851         ; return (NonRec bndr' rhs' : core_binds) }}
852
853 do_one (IfaceRec pairs) thing_inside
854   = do  { bndrs' <- mapM newExtCoreBndr bndrs
855         ; extendIfaceIdEnv bndrs' $ do
856         { rhss' <- mapM tcIfaceExpr rhss
857         ; core_binds <- thing_inside
858         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
859   where
860     (bndrs,rhss) = unzip pairs
861 \end{code}
862
863
864 %************************************************************************
865 %*                                                                      *
866                 IdInfo
867 %*                                                                      *
868 %************************************************************************
869
870 \begin{code}
871 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
872 tcIdInfo ignore_prags name ty info 
873   | ignore_prags = return vanillaIdInfo
874   | otherwise    = case info of
875                         NoInfo       -> return vanillaIdInfo
876                         HasInfo info -> foldlM tcPrag init_info info
877   where
878     -- Set the CgInfo to something sensible but uninformative before
879     -- we start; default assumption is that it has CAFs
880     init_info = vanillaIdInfo
881
882     tcPrag info HsNoCafRefs         = return (info `setCafInfo`   NoCafRefs)
883     tcPrag info (HsArity arity)     = return (info `setArityInfo` arity)
884     tcPrag info (HsStrictness str)  = return (info `setAllStrictnessInfo` Just str)
885
886         -- The next two are lazy, so they don't transitively suck stuff in
887     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
888     tcPrag info (HsInline inline_prag) = return (info `setInlinePragInfo` inline_prag)
889     tcPrag info (HsUnfold expr) = do
890           maybe_expr' <- tcPragExpr name expr
891           let
892                 -- maybe_expr' doesn't get looked at if the unfolding
893                 -- is never inspected; so the typecheck doesn't even happen
894                 unfold_info = case maybe_expr' of
895                                 Nothing    -> noUnfolding
896                                 Just expr' -> mkTopUnfolding expr' 
897           return (info `setUnfoldingInfoLazily` unfold_info)
898 \end{code}
899
900 \begin{code}
901 tcWorkerInfo ty info wkr arity
902   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
903
904         -- We return without testing maybe_wkr_id, but as soon as info is
905         -- looked at we will test it.  That's ok, because its outside the
906         -- knot; and there seems no big reason to further defer the
907         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
908         -- over the unfolding until it's actually used does seem worth while.)
909         ; us <- newUniqueSupply
910
911         ; return (case mb_wkr_id of
912                      Nothing     -> info
913                      Just wkr_id -> add_wkr_info us wkr_id info) }
914   where
915     doc = text "Worker for" <+> ppr wkr
916     add_wkr_info us wkr_id info
917         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
918                `setWorkerInfo`           HasWorker wkr_id arity
919
920     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
921
922         -- We are relying here on strictness info always appearing 
923         -- before worker info,  fingers crossed ....
924     strict_sig = case newStrictnessInfo info of
925                    Just sig -> sig
926                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr)
927 \end{code}
928
929 For unfoldings we try to do the job lazily, so that we never type check
930 an unfolding that isn't going to be looked at.
931
932 \begin{code}
933 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
934 tcPragExpr name expr
935   = forkM_maybe doc $ do
936     core_expr' <- tcIfaceExpr expr
937
938                 -- Check for type consistency in the unfolding
939     ifOptM Opt_DoCoreLinting $ do
940         in_scope <- get_in_scope_ids
941         case lintUnfolding noSrcLoc in_scope core_expr' of
942           Nothing       -> return ()
943           Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
944
945     return core_expr'
946   where
947     doc = text "Unfolding of" <+> ppr name
948     get_in_scope_ids    -- Urgh; but just for linting
949         = setLclEnv () $ 
950           do    { env <- getGblEnv 
951                 ; case if_rec_types env of {
952                           Nothing -> return [] ;
953                           Just (_, get_env) -> do
954                 { type_env <- get_env
955                 ; return (typeEnvIds type_env) }}}
956 \end{code}
957
958
959
960 %************************************************************************
961 %*                                                                      *
962                 Getting from Names to TyThings
963 %*                                                                      *
964 %************************************************************************
965
966 \begin{code}
967 tcIfaceGlobal :: Name -> IfL TyThing
968 tcIfaceGlobal name
969   | Just thing <- wiredInNameTyThing_maybe name
970         -- Wired-in things include TyCons, DataCons, and Ids
971   = do { ifCheckWiredInThing name; return thing }
972   | otherwise
973   = do  { env <- getGblEnv
974         ; case if_rec_types env of {    -- Note [Tying the knot]
975             Just (mod, get_type_env) 
976                 | nameIsLocalOrFrom mod name
977                 -> do           -- It's defined in the module being compiled
978                 { type_env <- setLclEnv () get_type_env         -- yuk
979                 ; case lookupNameEnv type_env name of
980                         Just thing -> return thing
981                         Nothing    -> pprPanic "tcIfaceGlobal (local): not found:"  
982                                                 (ppr name $$ ppr type_env) }
983
984           ; other -> do
985
986         { (eps,hpt) <- getEpsAndHpt
987         ; dflags <- getDOpts
988         ; case lookupType dflags hpt (eps_PTE eps) name of {
989             Just thing -> return thing ;
990             Nothing    -> do
991
992         { mb_thing <- importDecl name   -- It's imported; go get it
993         ; case mb_thing of
994             Failed err      -> failIfM err
995             Succeeded thing -> return thing
996     }}}}}
997
998 -- Note [Tying the knot]
999 -- ~~~~~~~~~~~~~~~~~~~~~
1000 -- The if_rec_types field is used in two situations:
1001 --
1002 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1003 --    Then we look up M.T in M's type environment, which is splatted into if_rec_types
1004 --    after we've built M's type envt.
1005 --
1006 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1007 --    is up to date.  So we call typecheckIface on M.hi.  This splats M.T into 
1008 --    if_rec_types so that the (lazily typechecked) decls see all the other decls
1009 --
1010 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1011 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1012 -- emasculated form (e.g. lacking data constructors).
1013
1014 ifCheckWiredInThing :: Name -> IfL ()
1015 -- Even though we are in an interface file, we want to make
1016 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
1017 -- Ditto want to ensure that RULES are loaded too
1018 -- See Note [Loading instances] in LoadIface
1019 ifCheckWiredInThing name 
1020   = do  { mod <- getIfModule
1021                 -- Check whether we are typechecking the interface for this
1022                 -- very module.  E.g when compiling the base library in --make mode
1023                 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
1024                 -- the HPT, so without the test we'll demand-load it into the PIT!
1025                 -- C.f. the same test in checkWiredInTyCon above
1026         ; unless (mod == nameModule name)
1027                  (loadWiredInHomeIface name) }
1028
1029 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1030 tcIfaceTyCon IfaceIntTc         = tcWiredInTyCon intTyCon
1031 tcIfaceTyCon IfaceBoolTc        = tcWiredInTyCon boolTyCon
1032 tcIfaceTyCon IfaceCharTc        = tcWiredInTyCon charTyCon
1033 tcIfaceTyCon IfaceListTc        = tcWiredInTyCon listTyCon
1034 tcIfaceTyCon IfacePArrTc        = tcWiredInTyCon parrTyCon
1035 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1036 tcIfaceTyCon (IfaceTc name)     = do { thing <- tcIfaceGlobal name 
1037                                      ; return (check_tc (tyThingTyCon thing)) }
1038   where
1039     check_tc tc
1040      | debugIsOn = case toIfaceTyCon tc of
1041                    IfaceTc _ -> tc
1042                    other     -> pprTrace "check_tc" (ppr tc) tc
1043      | otherwise = tc
1044 -- we should be okay just returning Kind constructors without extra loading
1045 tcIfaceTyCon IfaceLiftedTypeKindTc   = return liftedTypeKindTyCon
1046 tcIfaceTyCon IfaceOpenTypeKindTc     = return openTypeKindTyCon
1047 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1048 tcIfaceTyCon IfaceArgTypeKindTc      = return argTypeKindTyCon
1049 tcIfaceTyCon IfaceUbxTupleKindTc     = return ubxTupleKindTyCon
1050
1051 -- Even though we are in an interface file, we want to make
1052 -- sure the instances and RULES of this tycon are loaded 
1053 -- Imagine: f :: Double -> Double
1054 tcWiredInTyCon :: TyCon -> IfL TyCon
1055 tcWiredInTyCon tc = do { ifCheckWiredInThing (tyConName tc)
1056                        ; return tc }
1057
1058 tcIfaceClass :: Name -> IfL Class
1059 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1060                        ; return (tyThingClass thing) }
1061
1062 tcIfaceDataCon :: Name -> IfL DataCon
1063 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1064                          ; case thing of
1065                                 ADataCon dc -> return dc
1066                                 other   -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1067
1068 tcIfaceExtId :: Name -> IfL Id
1069 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1070                        ; case thing of
1071                           AnId id -> return id
1072                           other   -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1073 \end{code}
1074
1075 %************************************************************************
1076 %*                                                                      *
1077                 Bindings
1078 %*                                                                      *
1079 %************************************************************************
1080
1081 \begin{code}
1082 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1083 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1084   = do  { name <- newIfaceName (mkVarOccFS fs)
1085         ; ty' <- tcIfaceType ty
1086         ; let id = mkLocalId name ty'
1087         ; extendIfaceIdEnv [id] (thing_inside id) }
1088 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1089   = bindIfaceTyVar bndr thing_inside
1090     
1091 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1092 bindIfaceBndrs []     thing_inside = thing_inside []
1093 bindIfaceBndrs (b:bs) thing_inside
1094   = bindIfaceBndr b     $ \ b' ->
1095     bindIfaceBndrs bs   $ \ bs' ->
1096     thing_inside (b':bs')
1097
1098 -----------------------
1099 tcIfaceLetBndr (IfLetBndr fs ty info)
1100   = do  { name <- newIfaceName (mkVarOccFS fs)
1101         ; ty' <- tcIfaceType ty
1102         ; case info of
1103                 NoInfo    -> return (mkLocalId name ty')
1104                 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) } 
1105   where
1106         -- Similar to tcIdInfo, but much simpler
1107     tc_info [] = vanillaIdInfo
1108     tc_info (HsInline p     : i) = tc_info i `setInlinePragInfo` p 
1109     tc_info (HsArity a      : i) = tc_info i `setArityInfo` a 
1110     tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s 
1111     tc_info (other          : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo" 
1112                                             (ppr other) (tc_info i)
1113
1114 -----------------------
1115 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1116 newExtCoreBndr (IfLetBndr var ty _)    -- Ignoring IdInfo for now
1117   = do  { mod <- getIfModule
1118         ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1119         ; ty' <- tcIfaceType ty
1120         ; return (mkLocalId name ty') }
1121
1122 -----------------------
1123 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1124 bindIfaceTyVar (occ,kind) thing_inside
1125   = do  { name <- newIfaceName (mkTyVarOcc occ)
1126         ; tyvar <- mk_iface_tyvar name kind
1127         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1128
1129 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1130 bindIfaceTyVars bndrs thing_inside
1131   = do  { names <- newIfaceNames (map mkTyVarOcc occs)
1132         ; tyvars <- zipWithM mk_iface_tyvar names kinds
1133         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1134   where
1135     (occs,kinds) = unzip bndrs
1136
1137 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1138 mk_iface_tyvar name ifKind
1139    = do { kind <- tcIfaceType ifKind
1140         ; if isCoercionKind kind then 
1141                 return (Var.mkCoVar name kind)
1142           else
1143                 return (Var.mkTyVar name kind) }
1144 \end{code}
1145