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