Get of fam inst index in ifaces
[ghc-hetmet.git] / compiler / iface / TcIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcIfaceSig]{Type checking of type signatures in interface files}
5
6 \begin{code}
7 module TcIface ( 
8         tcImportDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface, 
9         tcIfaceDecl, tcIfaceInst, tcIfaceRule, tcIfaceGlobal, 
10         tcExtCoreBindings
11  ) where
12
13 #include "HsVersions.h"
14
15 import IfaceSyn
16 import LoadIface        ( loadInterface, loadWiredInHomeIface,
17                           loadDecls, findAndReadIface )
18 import IfaceEnv         ( lookupIfaceTop, lookupIfaceExt, newGlobalBinder, 
19                           extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
20                           tcIfaceTyVar, tcIfaceLclId, lookupIfaceTc, 
21                           newIfaceName, newIfaceNames, ifaceExportNames )
22 import BuildTyCl        ( buildSynTyCon, buildAlgTyCon, buildDataCon,
23                           buildClass, 
24                           mkAbstractTyConRhs, mkOpenDataTyConRhs,
25                           mkOpenNewTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
26 import TcRnMonad
27 import Type             ( liftedTypeKind, splitTyConApp, mkTyConApp,
28                           liftedTypeKindTyCon, unliftedTypeKindTyCon, 
29                           openTypeKindTyCon, argTypeKindTyCon, 
30                           ubxTupleKindTyCon,
31                           mkTyVarTys, ThetaType )
32 import TypeRep          ( Type(..), PredType(..) )
33 import TyCon            ( TyCon, tyConName, SynTyConRhs(..), 
34                           AlgTyConParent(..), setTyConArgPoss )
35 import HscTypes         ( ExternalPackageState(..), 
36                           TyThing(..), tyThingClass, tyThingTyCon, 
37                           ModIface(..), ModDetails(..), HomeModInfo(..),
38                           emptyModDetails, lookupTypeEnv, lookupType, typeEnvIds )
39 import InstEnv          ( Instance(..), mkImportedInstance )
40 import CoreSyn
41 import CoreUtils        ( exprType, dataConRepFSInstPat )
42 import CoreUnfold
43 import CoreLint         ( lintUnfolding )
44 import WorkWrap         ( mkWrapper )
45 import Id               ( Id, mkVanillaGlobal, mkLocalId )
46 import MkId             ( mkFCallId )
47 import IdInfo           ( IdInfo, CafInfo(..), WorkerInfo(..), 
48                           setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
49                           setArityInfo, setInlinePragInfo, setCafInfo, 
50                           vanillaIdInfo, newStrictnessInfo )
51 import Class            ( Class )
52 import TyCon            ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
53 import DataCon          ( DataCon, dataConWorkId, dataConExTyVars, dataConInstArgTys )
54 import TysWiredIn       ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
55 import Var              ( TyVar, mkTyVar, tyVarKind )
56 import Name             ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
57                           nameOccName, wiredInNameTyThing_maybe )
58 import NameEnv
59 import OccName          ( OccName, mkVarOccFS, mkTyVarOcc, occNameSpace, 
60                           pprNameSpace, occNameFS  )
61 import FastString       ( FastString )
62 import Module           ( Module, moduleName )
63 import UniqFM           ( lookupUFM )
64 import UniqSupply       ( initUs_, uniqsFromSupply )
65 import Outputable       
66 import ErrUtils         ( Message )
67 import Maybes           ( MaybeErr(..) )
68 import SrcLoc           ( noSrcLoc )
69 import Util             ( zipWithEqual, equalLength, splitAtList )
70 import DynFlags         ( DynFlag(..), isOneShot )
71
72 import List             ( elemIndex)
73 import Maybe            ( catMaybes )
74 import Monad            ( liftM )
75 \end{code}
76
77 This module takes
78
79         IfaceDecl -> TyThing
80         IfaceType -> Type
81         etc
82
83 An IfaceDecl is populated with RdrNames, and these are not renamed to
84 Names before typechecking, because there should be no scope errors etc.
85
86         -- For (b) consider: f = $(...h....)
87         -- where h is imported, and calls f via an hi-boot file.  
88         -- This is bad!  But it is not seen as a staging error, because h
89         -- is indeed imported.  We don't want the type-checker to black-hole 
90         -- when simplifying and compiling the splice!
91         --
92         -- Simple solution: discard any unfolding that mentions a variable
93         -- bound in this module (and hence not yet processed).
94         -- The discarding happens when forkM finds a type error.
95
96 %************************************************************************
97 %*                                                                      *
98 %*      tcImportDecl is the key function for "faulting in"              *
99 %*      imported things
100 %*                                                                      *
101 %************************************************************************
102
103 The main idea is this.  We are chugging along type-checking source code, and
104 find a reference to GHC.Base.map.  We call tcLookupGlobal, which doesn't find
105 it in the EPS type envt.  So it 
106         1 loads GHC.Base.hi
107         2 gets the decl for GHC.Base.map
108         3 typechecks it via tcIfaceDecl
109         4 and adds it to the type env in the EPS
110
111 Note that DURING STEP 4, we may find that map's type mentions a type 
112 constructor that also 
113
114 Notice that for imported things we read the current version from the EPS
115 mutable variable.  This is important in situations like
116         ...$(e1)...$(e2)...
117 where the code that e1 expands to might import some defns that 
118 also turn out to be needed by the code that e2 expands to.
119
120 \begin{code}
121 tcImportDecl :: Name -> TcM TyThing
122 -- Entry point for *source-code* uses of importDecl
123 tcImportDecl name 
124   | Just thing <- wiredInNameTyThing_maybe name
125   = do  { initIfaceTcRn (loadWiredInHomeIface name) 
126         ; return thing }
127   | otherwise
128   = do  { traceIf (text "tcImportDecl" <+> ppr name)
129         ; mb_thing <- initIfaceTcRn (importDecl name)
130         ; case mb_thing of
131             Succeeded thing -> return thing
132             Failed err      -> failWithTc err }
133
134 checkWiredInTyCon :: TyCon -> TcM ()
135 -- Ensure that the home module of the TyCon (and hence its instances)
136 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
137 -- in which case this is a no-op.
138 checkWiredInTyCon tc    
139   | not (isWiredInName tc_name) 
140   = return ()
141   | otherwise
142   = do  { mod <- getModule
143         ; if nameIsLocalOrFrom mod tc_name then
144                 -- Don't look for (non-existent) Float.hi when
145                 -- compiling Float.lhs, which mentions Float of course
146                 return ()
147           else  -- A bit yukky to call initIfaceTcRn here
148                 initIfaceTcRn (loadWiredInHomeIface tc_name) 
149         }
150   where
151     tc_name = tyConName tc
152
153 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
154 -- Get the TyThing for this Name from an interface file
155 -- It's not a wired-in thing -- the caller caught that
156 importDecl name
157   = ASSERT( not (isWiredInName name) )
158     do  { traceIf nd_doc
159
160         -- Load the interface, which should populate the PTE
161         ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
162         ; case mb_iface of {
163                 Failed err_msg  -> return (Failed err_msg) ;
164                 Succeeded iface -> do
165
166         -- Now look it up again; this time we should find it
167         { eps <- getEps 
168         ; case lookupTypeEnv (eps_PTE eps) name of
169             Just thing -> return (Succeeded thing)
170             Nothing    -> return (Failed not_found_msg)
171     }}}
172   where
173     nd_doc = ptext SLIT("Need decl for") <+> ppr name
174     not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+>
175                                 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
176                        2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
177                                 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
178 \end{code}
179
180 %************************************************************************
181 %*                                                                      *
182                 Type-checking a complete interface
183 %*                                                                      *
184 %************************************************************************
185
186 Suppose we discover we don't need to recompile.  Then we must type
187 check the old interface file.  This is a bit different to the
188 incremental type checking we do as we suck in interface files.  Instead
189 we do things similarly as when we are typechecking source decls: we
190 bring into scope the type envt for the interface all at once, using a
191 knot.  Remember, the decls aren't necessarily in dependency order --
192 and even if they were, the type decls might be mutually recursive.
193
194 \begin{code}
195 typecheckIface :: ModIface      -- Get the decls from here
196                -> TcRnIf gbl lcl ModDetails
197 typecheckIface iface
198   = initIfaceTc iface $ \ tc_env_var -> do
199         -- The tc_env_var is freshly allocated, private to 
200         -- type-checking this particular interface
201         {       -- Get the right set of decls and rules.  If we are compiling without -O
202                 -- we discard pragmas before typechecking, so that we don't "see"
203                 -- information that we shouldn't.  From a versioning point of view
204                 -- It's not actually *wrong* to do so, but in fact GHCi is unable 
205                 -- to handle unboxed tuples, so it must not see unfoldings.
206           ignore_prags <- doptM Opt_IgnoreInterfacePragmas
207
208                 -- Load & typecheck the decls
209         ; decl_things <- loadDecls ignore_prags (mi_decls iface)
210
211         ; let type_env = mkNameEnv decl_things
212         ; writeMutVar tc_env_var type_env
213
214                 -- Now do those rules and instances
215         ; let { rules | ignore_prags = []
216                       | otherwise    = mi_rules iface
217               ; dfuns = mi_insts iface
218               } 
219         ; dfuns <- mapM tcIfaceInst dfuns
220         ; rules <- mapM tcIfaceRule rules
221
222                 -- Exports
223         ; exports <-  ifaceExportNames (mi_exports iface)
224
225                 -- Finished
226         ; return (ModDetails {  md_types = type_env, 
227                                 md_insts = dfuns,
228                                 md_rules = rules,
229                                 md_exports = exports }) 
230     }
231 \end{code}
232
233
234 %************************************************************************
235 %*                                                                      *
236                 Type and class declarations
237 %*                                                                      *
238 %************************************************************************
239
240 \begin{code}
241 tcHiBootIface :: Module -> TcRn ModDetails
242 -- Load the hi-boot iface for the module being compiled,
243 -- if it indeed exists in the transitive closure of imports
244 -- Return the ModDetails, empty if no hi-boot iface
245 tcHiBootIface mod
246   = do  { traceIf (text "loadHiBootInterface" <+> ppr mod)
247
248         ; mode <- getGhcMode
249         ; if not (isOneShot mode)
250                 -- In --make and interactive mode, if this module has an hs-boot file
251                 -- we'll have compiled it already, and it'll be in the HPT
252                 -- 
253                 -- We check wheher the interface is a *boot* interface.
254                 -- It can happen (when using GHC from Visual Studio) that we
255                 -- compile a module in TypecheckOnly mode, with a stable, 
256                 -- fully-populated HPT.  In that case the boot interface isn't there
257                 -- (it's been replaced by the mother module) so we can't check it.
258                 -- And that's fine, because if M's ModInfo is in the HPT, then 
259                 -- it's been compiled once, and we don't need to check the boot iface
260           then do { hpt <- getHpt
261                   ; case lookupUFM hpt (moduleName mod) of
262                       Just info | mi_boot (hm_iface info) 
263                                 -> return (hm_details info)
264                       other -> return emptyModDetails }
265           else do
266
267         -- OK, so we're in one-shot mode.  
268         -- In that case, we're read all the direct imports by now, 
269         -- so eps_is_boot will record if any of our imports mention us by 
270         -- way of hi-boot file
271         { eps <- getEps
272         ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
273             Nothing -> return emptyModDetails ; -- The typical case
274
275             Just (_, False) -> failWithTc moduleLoop ;
276                 -- Someone below us imported us!
277                 -- This is a loop with no hi-boot in the way
278                 
279             Just (_mod, True) ->        -- There's a hi-boot interface below us
280                 
281     do  { read_result <- findAndReadIface 
282                                 need mod
283                                 True    -- Hi-boot file
284
285         ; case read_result of
286                 Failed err               -> failWithTc (elaborate err)
287                 Succeeded (iface, _path) -> typecheckIface iface
288     }}}}
289   where
290     need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
291                  <+> ptext SLIT("to compare against the Real Thing")
292
293     moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod) 
294                      <+> ptext SLIT("depends on itself")
295
296     elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+> 
297                           quotes (ppr mod) <> colon) 4 err
298 \end{code}
299
300
301 %************************************************************************
302 %*                                                                      *
303                 Type and class declarations
304 %*                                                                      *
305 %************************************************************************
306
307 When typechecking a data type decl, we *lazily* (via forkM) typecheck
308 the constructor argument types.  This is in the hope that we may never
309 poke on those argument types, and hence may never need to load the
310 interface files for types mentioned in the arg types.
311
312 E.g.    
313         data Foo.S = MkS Baz.T
314 Mabye we can get away without even loading the interface for Baz!
315
316 This is not just a performance thing.  Suppose we have
317         data Foo.S = MkS Baz.T
318         data Baz.T = MkT Foo.S
319 (in different interface files, of course).
320 Now, first we load and typecheck Foo.S, and add it to the type envt.  
321 If we do explore MkS's argument, we'll load and typecheck Baz.T.
322 If we explore MkT's argument we'll find Foo.S already in the envt.  
323
324 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
325 typecheck the type Baz.T.  So we'd fault in Baz.T... and then need Foo.S...
326 which isn't done yet.
327
328 All very cunning. However, there is a rather subtle gotcha which bit
329 me when developing this stuff.  When we typecheck the decl for S, we
330 extend the type envt with S, MkS, and all its implicit Ids.  Suppose
331 (a bug, but it happened) that the list of implicit Ids depended in
332 turn on the constructor arg types.  Then the following sequence of
333 events takes place:
334         * we build a thunk <t> for the constructor arg tys
335         * we build a thunk for the extended type environment (depends on <t>)
336         * we write the extended type envt into the global EPS mutvar
337         
338 Now we look something up in the type envt
339         * that pulls on <t>
340         * which reads the global type envt out of the global EPS mutvar
341         * but that depends in turn on <t>
342
343 It's subtle, because, it'd work fine if we typechecked the constructor args 
344 eagerly -- they don't need the extended type envt.  They just get the extended
345 type envt by accident, because they look at it later.
346
347 What this means is that the implicitTyThings MUST NOT DEPEND on any of
348 the forkM stuff.
349
350
351 \begin{code}
352 tcIfaceDecl :: IfaceDecl -> IfL TyThing
353
354 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
355   = do  { name <- lookupIfaceTop occ_name
356         ; ty <- tcIfaceType iface_type
357         ; info <- tcIdInfo name ty info
358         ; return (AnId (mkVanillaGlobal name ty info)) }
359
360 tcIfaceDecl (IfaceData {ifName = occ_name, 
361                         ifTyVars = tv_bndrs, 
362                         ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
363                         ifCons = rdr_cons, 
364                         ifRec = is_rec, 
365                         ifGeneric = want_generic,
366                         ifFamInst = mb_family })
367   = do  { tc_name <- lookupIfaceTop occ_name
368         ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
369
370         { tycon <- fixM ( \ tycon -> do
371             { stupid_theta <- tcIfaceCtxt ctxt
372             ; famInst <- 
373                 case mb_family of
374                   Nothing         -> return Nothing
375                   Just (fam, tys) -> 
376                     do { famTyCon <- tcIfaceTyCon fam
377                        ; insttys <- mapM tcIfaceType tys
378                        ; return $ Just (famTyCon, insttys)
379                        }
380             ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
381             ; buildAlgTyCon tc_name tyvars stupid_theta
382                             cons is_rec want_generic gadt_syn famInst
383             })
384         ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
385         ; return (ATyCon tycon)
386     }}
387
388 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs, 
389                        ifOpenSyn = isOpen, ifSynRhs = rdr_rhs_ty})
390    = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
391      { tc_name <- lookupIfaceTop occ_name
392      ; rhs_tyki <- tcIfaceType rdr_rhs_ty
393      ; let rhs = if isOpen then OpenSynTyCon rhs_tyki 
394                            else SynonymTyCon rhs_tyki
395      ; return (ATyCon (buildSynTyCon tc_name tyvars rhs))
396      }
397
398 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, 
399                          ifTyVars = tv_bndrs, ifFDs = rdr_fds, 
400                          ifATs = rdr_ats, ifSigs = rdr_sigs, 
401                          ifRec = tc_isrec })
402 -- ToDo: in hs-boot files we should really treat abstract classes specially,
403 --       as we do abstract tycons
404   = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
405     { cls_name <- lookupIfaceTop occ_name
406     ; ctxt <- tcIfaceCtxt rdr_ctxt
407     ; sigs <- mappM tc_sig rdr_sigs
408     ; fds  <- mappM tc_fd rdr_fds
409     ; ats'  <- mappM tcIfaceDecl rdr_ats
410     ; let ats = zipWith setTyThingPoss ats' (map ifTyVars rdr_ats)
411     ; cls  <- buildClass cls_name tyvars ctxt fds ats sigs tc_isrec
412     ; return (AClass cls) }
413   where
414    tc_sig (IfaceClassOp occ dm rdr_ty)
415      = do { op_name <- lookupIfaceTop occ
416           ; op_ty   <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
417                 -- Must be done lazily for just the same reason as the 
418                 -- context of a data decl: the type sig might mention the
419                 -- class being defined
420           ; return (op_name, dm, op_ty) }
421
422    mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
423
424    tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
425                            ; tvs2' <- mappM tcIfaceTyVar tvs2
426                            ; return (tvs1', tvs2') }
427
428    -- For each AT argument compute the position of the corresponding class
429    -- parameter in the class head.  This will later serve as a permutation
430    -- vector when checking the validity of instance declarations.
431    setTyThingPoss (ATyCon tycon) atTyVars = 
432      let classTyVars = map fst tv_bndrs
433          poss        =   catMaybes 
434                        . map ((`elemIndex` classTyVars) . fst) 
435                        $ atTyVars
436                     -- There will be no Nothing, as we already passed renaming
437      in 
438      ATyCon (setTyConArgPoss tycon poss)
439    setTyThingPoss _               _ = panic "TcIface.setTyThingPoss"
440
441 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
442   = do  { name <- lookupIfaceTop rdr_name
443         ; return (ATyCon (mkForeignTyCon name ext_name 
444                                          liftedTypeKind 0)) }
445
446 tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
447   = case if_cons of
448         IfAbstractTyCon  -> return mkAbstractTyConRhs
449         IfOpenDataTyCon  -> return mkOpenDataTyConRhs
450         IfOpenNewTyCon   -> return mkOpenNewTyConRhs
451         IfDataTyCon cons -> do  { data_cons <- mappM tc_con_decl cons
452                                 ; return (mkDataTyConRhs data_cons) }
453         IfNewTyCon con   -> do  { data_con <- tc_con_decl con
454                                 ; mkNewTyConRhs tycon_name tycon data_con }
455   where
456     tc_con_decl (IfCon { ifConInfix = is_infix, 
457                          ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
458                          ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
459                          ifConArgTys = args, ifConFields = field_lbls,
460                          ifConStricts = stricts})
461       = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
462         bindIfaceTyVars ex_tvs   $ \ ex_tyvars -> do
463         { name  <- lookupIfaceTop occ
464         ; eq_spec <- tcIfaceEqSpec spec
465         ; theta <- tcIfaceCtxt ctxt     -- Laziness seems not worth the bother here
466                 -- At one stage I thought that this context checking *had*
467                 -- to be lazy, because of possible mutual recursion between the
468                 -- type and the classe: 
469                 -- E.g. 
470                 --      class Real a where { toRat :: a -> Ratio Integer }
471                 --      data (Real a) => Ratio a = ...
472                 -- But now I think that the laziness in checking class ops breaks 
473                 -- the loop, so no laziness needed
474
475         -- Read the argument types, but lazily to avoid faulting in
476         -- the component types unless they are really needed
477         ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
478         ; lbl_names <- mappM lookupIfaceTop field_lbls
479
480         ; buildDataCon name is_infix {- Not infix -}
481                        stricts lbl_names
482                        univ_tyvars ex_tyvars 
483                        eq_spec theta 
484                        arg_tys tycon
485         }
486     mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
487
488 tcIfaceEqSpec spec
489   = mapM do_item spec
490   where
491     do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
492                               ; ty <- tcIfaceType if_ty
493                               ; return (tv,ty) }
494 \end{code}      
495
496
497 %************************************************************************
498 %*                                                                      *
499                 Instances
500 %*                                                                      *
501 %************************************************************************
502
503 \begin{code}
504 tcIfaceInst :: IfaceInst -> IfL Instance
505 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
506                          ifInstCls = cls, ifInstTys = mb_tcs,
507                          ifInstOrph = orph })
508   = do  { dfun    <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
509                      tcIfaceExtId (LocalTop dfun_occ)
510         ; cls'    <- lookupIfaceExt cls
511         ; mb_tcs' <- mapM do_tc mb_tcs
512         ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
513   where
514     do_tc Nothing   = return Nothing
515     do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
516 \end{code}
517
518
519 %************************************************************************
520 %*                                                                      *
521                 Rules
522 %*                                                                      *
523 %************************************************************************
524
525 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
526 are in the type environment.  However, remember that typechecking a Rule may 
527 (as a side effect) augment the type envt, and so we may need to iterate the process.
528
529 \begin{code}
530 tcIfaceRule :: IfaceRule -> IfL CoreRule
531 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
532                         ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
533                         ifRuleOrph = orph })
534   = do  { fn' <- lookupIfaceExt fn
535         ; ~(bndrs', args', rhs') <- 
536                 -- Typecheck the payload lazily, in the hope it'll never be looked at
537                 forkM (ptext SLIT("Rule") <+> ftext name) $
538                 bindIfaceBndrs bndrs                      $ \ bndrs' ->
539                 do { args' <- mappM tcIfaceExpr args
540                    ; rhs'  <- tcIfaceExpr rhs
541                    ; return (bndrs', args', rhs') }
542         ; mb_tcs <- mapM ifTopFreeName args
543         ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act, 
544                           ru_bndrs = bndrs', ru_args = args', 
545                           ru_rhs = rhs', ru_orph = orph,
546                           ru_rough = mb_tcs,
547                           ru_local = isLocalIfaceExtName fn }) }
548   where
549         -- This function *must* mirror exactly what Rules.topFreeName does
550         -- We could have stored the ru_rough field in the iface file
551         -- but that would be redundant, I think.
552         -- The only wrinkle is that we must not be deceived by
553         -- type syononyms at the top of a type arg.  Since
554         -- we can't tell at this point, we are careful not
555         -- to write them out in coreRuleToIfaceRule
556     ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
557     ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
558         = do { n <- lookupIfaceTc tc
559              ; return (Just n) }
560     ifTopFreeName (IfaceApp f a) = ifTopFreeName f
561     ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
562                                       ; return (Just n) }
563     ifTopFreeName other = return Nothing
564 \end{code}
565
566
567 %************************************************************************
568 %*                                                                      *
569                         Types
570 %*                                                                      *
571 %************************************************************************
572
573 \begin{code}
574 tcIfaceType :: IfaceType -> IfL Type
575 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
576 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
577 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
578 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
579 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
580 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
581
582 tcIfaceTypes tys = mapM tcIfaceType tys
583
584 -----------------------------------------
585 tcIfacePredType :: IfacePredType -> IfL PredType
586 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
587 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
588 tcIfacePredType (IfaceEqPred t1 t2)  = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
589
590 -----------------------------------------
591 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
592 tcIfaceCtxt sts = mappM tcIfacePredType sts
593 \end{code}
594
595
596 %************************************************************************
597 %*                                                                      *
598                         Core
599 %*                                                                      *
600 %************************************************************************
601
602 \begin{code}
603 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
604 tcIfaceExpr (IfaceType ty)
605   = tcIfaceType ty              `thenM` \ ty' ->
606     returnM (Type ty')
607
608 tcIfaceExpr (IfaceLcl name)
609   = tcIfaceLclId name   `thenM` \ id ->
610     returnM (Var id)
611
612 tcIfaceExpr (IfaceExt gbl)
613   = tcIfaceExtId gbl    `thenM` \ id ->
614     returnM (Var id)
615
616 tcIfaceExpr (IfaceLit lit)
617   = returnM (Lit lit)
618
619 tcIfaceExpr (IfaceFCall cc ty)
620   = tcIfaceType ty      `thenM` \ ty' ->
621     newUnique           `thenM` \ u ->
622     returnM (Var (mkFCallId u cc ty'))
623
624 tcIfaceExpr (IfaceTuple boxity args) 
625   = mappM tcIfaceExpr args      `thenM` \ args' ->
626     let
627         -- Put the missing type arguments back in
628         con_args = map (Type . exprType) args' ++ args'
629     in
630     returnM (mkApps (Var con_id) con_args)
631   where
632     arity = length args
633     con_id = dataConWorkId (tupleCon boxity arity)
634     
635
636 tcIfaceExpr (IfaceLam bndr body)
637   = bindIfaceBndr bndr          $ \ bndr' ->
638     tcIfaceExpr body            `thenM` \ body' ->
639     returnM (Lam bndr' body')
640
641 tcIfaceExpr (IfaceApp fun arg)
642   = tcIfaceExpr fun             `thenM` \ fun' ->
643     tcIfaceExpr arg             `thenM` \ arg' ->
644     returnM (App fun' arg')
645
646 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) 
647   = tcIfaceExpr scrut           `thenM` \ scrut' ->
648     newIfaceName (mkVarOccFS case_bndr) `thenM` \ case_bndr_name ->
649     let
650         scrut_ty   = exprType scrut'
651         case_bndr' = mkLocalId case_bndr_name scrut_ty
652         tc_app     = splitTyConApp scrut_ty
653                 -- NB: Won't always succeed (polymoprhic case)
654                 --     but won't be demanded in those cases
655                 -- NB: not tcSplitTyConApp; we are looking at Core here
656                 --     look through non-rec newtypes to find the tycon that
657                 --     corresponds to the datacon in this case alternative
658     in
659     extendIfaceIdEnv [case_bndr']       $
660     mappM (tcIfaceAlt tc_app) alts      `thenM` \ alts' ->
661     tcIfaceType ty              `thenM` \ ty' ->
662     returnM (Case scrut' case_bndr' ty' alts')
663
664 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
665   = tcIfaceExpr rhs             `thenM` \ rhs' ->
666     bindIfaceId bndr            $ \ bndr' ->
667     tcIfaceExpr body            `thenM` \ body' ->
668     returnM (Let (NonRec bndr' rhs') body')
669
670 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
671   = bindIfaceIds bndrs          $ \ bndrs' ->
672     mappM tcIfaceExpr rhss      `thenM` \ rhss' ->
673     tcIfaceExpr body            `thenM` \ body' ->
674     returnM (Let (Rec (bndrs' `zip` rhss')) body')
675   where
676     (bndrs, rhss) = unzip pairs
677
678 tcIfaceExpr (IfaceCast expr co) = do
679   expr' <- tcIfaceExpr expr
680   co' <- tcIfaceType co
681   returnM (Cast expr' co')
682
683 tcIfaceExpr (IfaceNote note expr) 
684   = tcIfaceExpr expr            `thenM` \ expr' ->
685     case note of
686         IfaceInlineMe     -> returnM (Note InlineMe   expr')
687         IfaceSCC cc       -> returnM (Note (SCC cc)   expr')
688         IfaceCoreNote n   -> returnM (Note (CoreNote n) expr')
689
690 -------------------------
691 tcIfaceAlt _ (IfaceDefault, names, rhs)
692   = ASSERT( null names )
693     tcIfaceExpr rhs             `thenM` \ rhs' ->
694     returnM (DEFAULT, [], rhs')
695   
696 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
697   = ASSERT( null names )
698     tcIfaceExpr rhs             `thenM` \ rhs' ->
699     returnM (LitAlt lit, [], rhs')
700
701 -- A case alternative is made quite a bit more complicated
702 -- by the fact that we omit type annotations because we can
703 -- work them out.  True enough, but its not that easy!
704 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
705   = do  { let tycon_mod = nameModule (tyConName tycon)
706         ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
707         ; ASSERT2( con `elem` tyConDataCons tycon,
708                    ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
709           tcIfaceDataAlt con inst_tys arg_strs rhs }
710                   
711 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
712   = ASSERT( isTupleTyCon tycon )
713     do  { let [data_con] = tyConDataCons tycon
714         ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
715
716 tcIfaceDataAlt con inst_tys arg_strs rhs
717   = do  { us <- newUniqueSupply
718         ; let uniqs = uniqsFromSupply us
719         ; let (ex_tvs, co_tvs, arg_ids)
720                       = dataConRepFSInstPat arg_strs uniqs con inst_tys
721               all_tvs = ex_tvs ++ co_tvs
722
723         ; rhs' <- extendIfaceTyVarEnv all_tvs   $
724                   extendIfaceIdEnv arg_ids      $
725                   tcIfaceExpr rhs
726         ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
727 \end{code}
728
729
730 \begin{code}
731 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind]   -- Used for external core
732 tcExtCoreBindings []     = return []
733 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
734
735 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
736 do_one (IfaceNonRec bndr rhs) thing_inside
737   = do  { rhs' <- tcIfaceExpr rhs
738         ; bndr' <- newExtCoreBndr bndr
739         ; extendIfaceIdEnv [bndr'] $ do 
740         { core_binds <- thing_inside
741         ; return (NonRec bndr' rhs' : core_binds) }}
742
743 do_one (IfaceRec pairs) thing_inside
744   = do  { bndrs' <- mappM newExtCoreBndr bndrs
745         ; extendIfaceIdEnv bndrs' $ do
746         { rhss' <- mappM tcIfaceExpr rhss
747         ; core_binds <- thing_inside
748         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
749   where
750     (bndrs,rhss) = unzip pairs
751 \end{code}
752
753
754 %************************************************************************
755 %*                                                                      *
756                 IdInfo
757 %*                                                                      *
758 %************************************************************************
759
760 \begin{code}
761 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
762 tcIdInfo name ty NoInfo         = return vanillaIdInfo
763 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
764   where
765     -- Set the CgInfo to something sensible but uninformative before
766     -- we start; default assumption is that it has CAFs
767     init_info = vanillaIdInfo
768
769     tcPrag info HsNoCafRefs         = returnM (info `setCafInfo`   NoCafRefs)
770     tcPrag info (HsArity arity)     = returnM (info `setArityInfo` arity)
771     tcPrag info (HsStrictness str)  = returnM (info `setAllStrictnessInfo` Just str)
772
773         -- The next two are lazy, so they don't transitively suck stuff in
774     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
775     tcPrag info (HsInline inline_prag) = returnM (info `setInlinePragInfo` inline_prag)
776     tcPrag info (HsUnfold expr)
777         = tcPragExpr name expr  `thenM` \ maybe_expr' ->
778           let
779                 -- maybe_expr' doesn't get looked at if the unfolding
780                 -- is never inspected; so the typecheck doesn't even happen
781                 unfold_info = case maybe_expr' of
782                                 Nothing    -> noUnfolding
783                                 Just expr' -> mkTopUnfolding expr' 
784           in
785           returnM (info `setUnfoldingInfoLazily` unfold_info)
786 \end{code}
787
788 \begin{code}
789 tcWorkerInfo ty info wkr arity
790   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
791
792         -- We return without testing maybe_wkr_id, but as soon as info is
793         -- looked at we will test it.  That's ok, because its outside the
794         -- knot; and there seems no big reason to further defer the
795         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
796         -- over the unfolding until it's actually used does seem worth while.)
797         ; us <- newUniqueSupply
798
799         ; returnM (case mb_wkr_id of
800                      Nothing     -> info
801                      Just wkr_id -> add_wkr_info us wkr_id info) }
802   where
803     doc = text "Worker for" <+> ppr wkr
804     add_wkr_info us wkr_id info
805         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
806                `setWorkerInfo`           HasWorker wkr_id arity
807
808     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
809
810         -- We are relying here on strictness info always appearing 
811         -- before worker info,  fingers crossed ....
812     strict_sig = case newStrictnessInfo info of
813                    Just sig -> sig
814                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr)
815 \end{code}
816
817 For unfoldings we try to do the job lazily, so that we never type check
818 an unfolding that isn't going to be looked at.
819
820 \begin{code}
821 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
822 tcPragExpr name expr
823   = forkM_maybe doc $
824     tcIfaceExpr expr            `thenM` \ core_expr' ->
825
826                 -- Check for type consistency in the unfolding
827     ifOptM Opt_DoCoreLinting (
828         get_in_scope_ids                        `thenM` \ in_scope -> 
829         case lintUnfolding noSrcLoc in_scope core_expr' of
830           Nothing       -> returnM ()
831           Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
832     )                           `thenM_`
833
834    returnM core_expr'   
835   where
836     doc = text "Unfolding of" <+> ppr name
837     get_in_scope_ids    -- Urgh; but just for linting
838         = setLclEnv () $ 
839           do    { env <- getGblEnv 
840                 ; case if_rec_types env of {
841                           Nothing -> return [] ;
842                           Just (_, get_env) -> do
843                 { type_env <- get_env
844                 ; return (typeEnvIds type_env) }}}
845 \end{code}
846
847
848
849 %************************************************************************
850 %*                                                                      *
851                 Getting from Names to TyThings
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 tcIfaceGlobal :: Name -> IfL TyThing
857 tcIfaceGlobal name
858   | Just thing <- wiredInNameTyThing_maybe name
859         -- Wired-in things include TyCons, DataCons, and Ids
860   = do { loadWiredInHomeIface name; return thing }
861         -- Even though we are in an interface file, we want to make
862         -- sure its instances are loaded (imagine f :: Double -> Double)
863         -- and its RULES are loaded too
864   | otherwise
865   = do  { (eps,hpt) <- getEpsAndHpt
866         ; dflags <- getDOpts
867         ; case lookupType dflags hpt (eps_PTE eps) name of {
868             Just thing -> return thing ;
869             Nothing    -> do
870
871         { env <- getGblEnv
872         ; case if_rec_types env of {
873             Just (mod, get_type_env) 
874                 | nameIsLocalOrFrom mod name
875                 -> do           -- It's defined in the module being compiled
876                 { type_env <- setLclEnv () get_type_env         -- yuk
877                 ; case lookupNameEnv type_env name of
878                         Just thing -> return thing
879                         Nothing    -> pprPanic "tcIfaceGlobal (local): not found:"  
880                                                 (ppr name $$ ppr type_env) }
881
882           ; other -> do
883
884         { mb_thing <- importDecl name   -- It's imported; go get it
885         ; case mb_thing of
886             Failed err      -> failIfM err
887             Succeeded thing -> return thing
888     }}}}}
889
890 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
891 tcIfaceTyCon IfaceIntTc         = tcWiredInTyCon intTyCon
892 tcIfaceTyCon IfaceBoolTc        = tcWiredInTyCon boolTyCon
893 tcIfaceTyCon IfaceCharTc        = tcWiredInTyCon charTyCon
894 tcIfaceTyCon IfaceListTc        = tcWiredInTyCon listTyCon
895 tcIfaceTyCon IfacePArrTc        = tcWiredInTyCon parrTyCon
896 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
897 tcIfaceTyCon (IfaceTc ext_nm)   = do { name <- lookupIfaceExt ext_nm
898                                      ; thing <- tcIfaceGlobal name 
899                                      ; return (check_tc (tyThingTyCon thing)) }
900   where
901 #ifdef DEBUG
902     check_tc tc = case toIfaceTyCon (error "urk") tc of
903                    IfaceTc _ -> tc
904                    other     -> pprTrace "check_tc" (ppr tc) tc
905 #else
906     check_tc tc = tc
907 #endif
908 -- we should be okay just returning Kind constructors without extra loading
909 tcIfaceTyCon IfaceLiftedTypeKindTc   = return liftedTypeKindTyCon
910 tcIfaceTyCon IfaceOpenTypeKindTc     = return openTypeKindTyCon
911 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
912 tcIfaceTyCon IfaceArgTypeKindTc      = return argTypeKindTyCon
913 tcIfaceTyCon IfaceUbxTupleKindTc     = return ubxTupleKindTyCon
914
915 -- Even though we are in an interface file, we want to make
916 -- sure the instances and RULES of this tycon are loaded 
917 -- Imagine: f :: Double -> Double
918 tcWiredInTyCon :: TyCon -> IfL TyCon
919 tcWiredInTyCon tc = do { loadWiredInHomeIface (tyConName tc)
920                        ; return tc }
921
922 tcIfaceClass :: IfaceExtName -> IfL Class
923 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
924                            ; thing <- tcIfaceGlobal name
925                            ; return (tyThingClass thing) }
926
927 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
928 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
929                         ; thing <- tcIfaceGlobal name
930                         ; case thing of
931                                 ADataCon dc -> return dc
932                                 other   -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
933
934 tcIfaceExtId :: IfaceExtName -> IfL Id
935 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
936                       ; thing <- tcIfaceGlobal name
937                       ; case thing of
938                           AnId id -> return id
939                           other   -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
940 \end{code}
941
942 %************************************************************************
943 %*                                                                      *
944                 Bindings
945 %*                                                                      *
946 %************************************************************************
947
948 \begin{code}
949 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
950 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
951   = bindIfaceId bndr thing_inside
952 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
953   = bindIfaceTyVar bndr thing_inside
954     
955 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
956 bindIfaceBndrs []     thing_inside = thing_inside []
957 bindIfaceBndrs (b:bs) thing_inside
958   = bindIfaceBndr b     $ \ b' ->
959     bindIfaceBndrs bs   $ \ bs' ->
960     thing_inside (b':bs')
961
962 -----------------------
963 bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
964 bindIfaceId (occ, ty) thing_inside
965   = do  { name <- newIfaceName (mkVarOccFS occ)
966         ; ty' <- tcIfaceType ty
967         ; let { id = mkLocalId name ty' }
968         ; extendIfaceIdEnv [id] (thing_inside id) }
969     
970 bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
971 bindIfaceIds bndrs thing_inside
972   = do  { names <- newIfaceNames (map mkVarOccFS occs)
973         ; tys' <- mappM tcIfaceType tys
974         ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
975         ; extendIfaceIdEnv ids (thing_inside ids) }
976   where
977     (occs,tys) = unzip bndrs
978
979
980 -----------------------
981 newExtCoreBndr :: IfaceIdBndr -> IfL Id
982 newExtCoreBndr (var, ty)
983   = do  { mod <- getIfModule
984         ; name <- newGlobalBinder mod (mkVarOccFS var) Nothing noSrcLoc
985         ; ty' <- tcIfaceType ty
986         ; return (mkLocalId name ty') }
987
988 -----------------------
989 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
990 bindIfaceTyVar (occ,kind) thing_inside
991   = do  { name <- newIfaceName (mkTyVarOcc occ)
992         ; tyvar <- mk_iface_tyvar name kind
993         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
994
995 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
996 bindIfaceTyVars bndrs thing_inside
997   = do  { names <- newIfaceNames (map mkTyVarOcc occs)
998         ; tyvars <- zipWithM mk_iface_tyvar names kinds
999         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1000   where
1001     (occs,kinds) = unzip bndrs
1002
1003 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1004 mk_iface_tyvar name ifKind = do { kind <- tcIfaceType ifKind
1005                                 ; return (mkTyVar name kind)
1006                                 }
1007 \end{code}
1008