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