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