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