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