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