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