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