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