[project @ 2004-04-02 13:19:28 by simonpj]
[ghc-hetmet.git] / ghc / 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, typecheckIface,
9         loadImportedInsts, loadImportedRules,
10         tcExtCoreBindings
11  ) where
12 #include "HsVersions.h"
13
14 import IfaceSyn
15 import LoadIface        ( loadHomeInterface, predInstGates, discardDeclPrags )
16 import IfaceEnv         ( lookupIfaceTop, newGlobalBinder, lookupOrig,
17                           extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
18                           tcIfaceTyVar, tcIfaceTyCon, tcIfaceClass, tcIfaceExtId,
19                           tcIfaceDataCon, tcIfaceLclId,
20                           newIfaceName, newIfaceNames )
21 import BuildTyCl        ( buildSynTyCon, buildAlgTyCon, buildDataCon, buildClass,
22                           mkAbstractTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
23 import TcRnMonad
24 import Type             ( liftedTypeKind, splitTyConApp, 
25                           mkTyVarTys, mkGenTyConApp, mkTyVarTys, ThetaType, pprClassPred )
26 import TypeRep          ( Type(..), PredType(..) )
27 import TyCon            ( TyCon, tyConName )
28 import HscTypes         ( ExternalPackageState(..), PackageInstEnv, PackageRuleBase,
29                           HscEnv, TyThing(..), implicitTyThings, typeEnvIds,
30                           ModIface(..), ModDetails(..), InstPool, ModGuts,
31                           TypeEnv, mkTypeEnv, extendTypeEnvList, lookupTypeEnv,
32                           RulePool, Pool(..) )
33 import InstEnv          ( extendInstEnv )
34 import CoreSyn
35 import PprCore          ( pprIdRules )
36 import Rules            ( extendRuleBaseList )
37 import CoreUtils        ( exprType )
38 import CoreUnfold
39 import CoreLint         ( lintUnfolding )
40 import WorkWrap         ( mkWrapper )
41 import InstEnv          ( DFunId )
42 import Id               ( Id, mkVanillaGlobal, mkLocalId )
43 import MkId             ( mkFCallId )
44 import IdInfo           ( IdInfo, CafInfo(..), WorkerInfo(..), 
45                           setUnfoldingInfoLazily, setAllStrictnessInfo, setWorkerInfo,
46                           setArityInfo, setInlinePragInfo, setCafInfo, 
47                           vanillaIdInfo, newStrictnessInfo )
48 import Class            ( Class )
49 import TyCon            ( AlgTyConRhs(..), tyConDataCons, tyConTyVars, isTupleTyCon, mkForeignTyCon )
50 import DataCon          ( dataConWorkId, dataConExistentialTyVars, dataConArgTys )
51 import TysWiredIn       ( tupleCon )
52 import Var              ( TyVar, mkTyVar, tyVarKind )
53 import Name             ( Name, NamedThing(..), nameModuleName, nameModule, nameOccName, 
54                           isWiredInName, wiredInNameTyThing_maybe, nameParent, nameParent_maybe )
55 import NameEnv
56 import OccName          ( OccName )
57 import Module           ( Module, ModuleName, moduleName )
58 import UniqSupply       ( initUs_ )
59 import Outputable       
60 import SrcLoc           ( noSrcLoc )
61 import Util             ( zipWithEqual, dropList, equalLength, zipLazy )
62 import Maybes           ( expectJust )
63 import CmdLineOpts      ( DynFlag(..), dopt )
64 \end{code}
65
66 This module takes
67
68         IfaceDecl -> TyThing
69         IfaceType -> Type
70         etc
71
72 An IfaceDecl is populated with RdrNames, and these are not renamed to
73 Names before typechecking, because there should be no scope errors etc.
74
75         -- For (b) consider: f = $(...h....)
76         -- where h is imported, and calls f via an hi-boot file.  
77         -- This is bad!  But it is not seen as a staging error, because h
78         -- is indeed imported.  We don't want the type-checker to black-hole 
79         -- when simplifying and compiling the splice!
80         --
81         -- Simple solution: discard any unfolding that mentions a variable
82         -- bound in this module (and hence not yet processed).
83         -- The discarding happens when forkM finds a type error.
84
85 %************************************************************************
86 %*                                                                      *
87 %*      tcImportDecl is the key function for "faulting in"              *
88 %*      imported things
89 %*                                                                      *
90 %************************************************************************
91
92 The main idea is this.  We are chugging along type-checking source code, and
93 find a reference to GHC.Base.map.  We call tcLookupGlobal, which doesn't find
94 it in the EPS type envt.  So it 
95         1 loads GHC.Base.hi
96         2 gets the decl for GHC.Base.map
97         3 typechecks it via tcIfaceDecl
98         4 and adds it to the type env in the EPS
99
100 Note that DURING STEP 4, we may find that map's type mentions a type 
101 constructor that also 
102
103 Notice that for imported things we read the current version from the EPS
104 mutable variable.  This is important in situations like
105         ...$(e1)...$(e2)...
106 where the code that e1 expands to might import some defns that 
107 also turn out to be needed by the code that e2 expands to.
108
109 \begin{code}
110 tcImportDecl :: Name -> IfG TyThing
111 -- Get the TyThing for this Name from an interface file
112 tcImportDecl name
113   = do  { 
114     -- Make sure the interface is loaded
115         ; let { nd_doc = ptext SLIT("Need decl for") <+> ppr name }
116         ; traceIf (nd_doc <+> char '{')         -- Brace matches the later message
117         ; loadHomeInterface nd_doc name
118
119     -- Get the real name of the thing, with a correct nameParent field.
120     -- Before the interface is loaded, we may have a non-committal 'Nothing'
121     -- in the namePareent field (made up by IfaceEnv.lookupOrig), but 
122     -- loading the interface updates the name cache.
123     -- We need the right nameParent field in getThing
124         ; real_name <- lookupOrig (nameModuleName name) (nameOccName name)
125
126     -- Get the decl out of the EPS
127         ; main_thing <- ASSERT( real_name == name )     -- Unique should not change!
128                         getThing real_name
129
130     -- Record the import in the type env, 
131     -- slurp any rules it allows in
132         ; recordImportOf main_thing
133
134         ; let { extra | getName main_thing == real_name = empty
135                       | otherwise = brackets (ptext SLIT("when seeking") <+> ppr real_name) }
136         ; traceIf (ptext SLIT(" ...imported decl for") <+> ppr main_thing <+> extra <+> char '}')
137
138
139     -- Look up the wanted Name in the type envt; it might be
140     -- one of the subordinate members of the input thing
141         ; if real_name == getName main_thing 
142           then return main_thing
143           else do
144         { eps <- getEps
145         ; return (expectJust "tcImportDecl" $
146                   lookupTypeEnv (eps_PTE eps) real_name) }}
147
148 recordImportOf :: TyThing -> IfG ()
149 -- Update the EPS to record the import of the Thing
150 --   (a) augment the type environment; this is done even for wired-in 
151 --       things, so that we don't go through this rigmarole a second time
152 --   (b) slurp in any rules to maintain the invariant that any rule
153 --           whose gates are all in the type envt, is in eps_rule_base
154
155 recordImportOf thing
156   = do  { new_things <- updateEps (\ eps -> 
157             let { new_things   = thing : implicitTyThings thing 
158                 ; new_type_env = extendTypeEnvList (eps_PTE eps) new_things
159                 -- NB: opportunity for a very subtle loop here!
160                 -- If working out what the implicitTyThings are involves poking
161                 -- any of the fork'd thunks in 'thing', then here's what happens        
162                 --      * recordImportOf succeed, extending type-env with a thunk
163                 --      * the next guy to pull on type-env forces the thunk
164                 --      * which pokes the suspended forks
165                 --      * which, to execute, need to consult type-env (to check
166                 --        entirely unrelated types, perhaps)
167             }
168             in (eps { eps_PTE = new_type_env }, new_things)
169           )
170         ; traceIf (text "tcImport: extend type env" <+> ppr new_things)
171         }
172         
173 getThing :: Name -> IfG TyThing
174 -- Find and typecheck the thing; the Name might be a "subordinate name"
175 -- of the "main thing" (e.g. the constructor of a data type declaration)
176 -- The Thing we return is the parent "main thing"
177
178 getThing name
179   | Just thing <- wiredInNameTyThing_maybe name
180    = return thing
181
182   | otherwise = do      -- The normal case, not wired in
183   {     -- Get the decl from the pool
184     mb_decl <- updateEps (\ eps -> selectDecl eps name)
185
186     ; case mb_decl of
187         Just decl -> initIfaceLcl (nameModuleName name) (tcIfaceDecl decl)
188                 -- Typecheck it
189                 -- Side-effects EPS by faulting in any needed decls
190                 -- (via nested calls to tcImportDecl)
191                      
192
193         Nothing -> do { ioToIOEnv (printErrs (msg defaultErrStyle)); failM }
194                 -- Declaration not found
195                 -- No errors-var to accumulate errors in, so just
196                 -- print out the error right now
197                      
198     }
199   where
200      msg = hang (ptext SLIT("Can't find interface-file declaration for") <+> ppr (nameParent name))
201               2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
202                        ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
203
204 selectDecl :: ExternalPackageState -> Name -> (ExternalPackageState, Maybe IfaceDecl)
205 -- Use nameParent to get the parent name of the thing
206 selectDecl eps@(EPS { eps_decls = Pool decls_map n_in n_out}) name
207    = case lookupNameEnv decls_map name of {
208                 -- This first lookup will usually fail for subordinate names, because
209                 -- the relevant decl is the parent decl.
210                 -- But, if we export a data type decl abstractly, its selectors
211                 -- get separate type signatures in the interface file
212         Just decl -> let 
213                         decls' = delFromNameEnv decls_map name
214                      in
215                      (eps {eps_decls = Pool decls' n_in (n_out+1)}, Just decl) ;
216
217         Nothing -> 
218     case nameParent_maybe name of {
219         Nothing        -> (eps, Nothing ) ;     -- No "parent" 
220         Just main_name ->                       -- Has a parent; try that
221
222     case lookupNameEnv decls_map main_name of {
223         Just decl -> let 
224                         decls' = delFromNameEnv decls_map main_name
225                      in
226                      (eps {eps_decls = Pool decls' n_in (n_out+1)}, Just decl) ;
227         Nothing   -> (eps, Nothing)
228     }}}
229 \end{code}
230
231 %************************************************************************
232 %*                                                                      *
233                 Type-checking a complete interface
234 %*                                                                      *
235 %************************************************************************
236
237 Suppose we discover we don't need to recompile.  Then we must type
238 check the old interface file.  This is a bit different to the
239 incremental type checking we do as we suck in interface files.  Instead
240 we do things similarly as when we are typechecking source decls: we
241 bring into scope the type envt for the interface all at once, using a
242 knot.  Remember, the decls aren't necessarily in dependency order --
243 and even if they were, the type decls might be mutually recursive.
244
245 \begin{code}
246 typecheckIface :: HscEnv
247                -> ModIface      -- Get the decls from here
248                -> IO ModDetails
249 typecheckIface hsc_env iface
250   = initIfaceTc hsc_env iface $ \ tc_env_var -> do
251         {       -- Get the right set of decls and rules.  If we are compiling without -O
252                 -- we discard pragmas before typechecking, so that we don't "see"
253                 -- information that we shouldn't.  From a versioning point of view
254                 -- It's not actually *wrong* to do so, but in fact GHCi is unable 
255                 -- to handle unboxed tuples, so it must not see unfoldings.
256           ignore_prags <- doptM Opt_IgnoreInterfacePragmas
257         ; let { decls | ignore_prags = map (discardDeclPrags . snd) (mi_decls iface)
258                       | otherwise    = map snd (mi_decls iface)
259               ; rules | ignore_prags = []
260                       | otherwise    = mi_rules iface
261               ; dfuns    = mi_insts iface
262               ; mod_name = moduleName (mi_module iface)
263           }
264                 -- Typecheck the decls
265         ; names <- mappM (lookupOrig mod_name . ifName) decls
266         ; ty_things <- fixM (\ rec_ty_things -> do
267                 { writeMutVar tc_env_var (mkNameEnv (names `zipLazy` rec_ty_things))
268                         -- This only makes available the "main" things,
269                         -- but that's enough for the strictly-checked part
270                 ; mapM tcIfaceDecl decls })
271         
272                 -- Now augment the type envt with all the implicit things
273                 -- These will be needed when type-checking the unfoldings for
274                 -- the IfaceIds, but this is done lazily, so writing the thing
275                 -- now is sufficient
276         ; let   { add_implicits main_thing = main_thing : implicitTyThings main_thing
277                 ; type_env = mkTypeEnv (concatMap add_implicits ty_things) }
278         ; writeMutVar tc_env_var type_env
279
280                 -- Now do those rules and instances
281         ; dfuns <- mapM tcIfaceInst dfuns
282         ; rules <- mapM tcIfaceRule rules
283
284                 -- Finished
285         ; return (ModDetails { md_types = type_env, md_insts = dfuns, md_rules = rules }) 
286     }
287 \end{code}
288
289
290 %************************************************************************
291 %*                                                                      *
292                 Type and class declarations
293 %*                                                                      *
294 %************************************************************************
295
296 When typechecking a data type decl, we *lazily* (via forkM) typecheck
297 the constructor argument types.  This is in the hope that we may never
298 poke on those argument types, and hence may never need to load the
299 interface files for types mentioned in the arg types.
300
301 E.g.    
302         data Foo.S = MkS Baz.T
303 Mabye we can get away without even loading the interface for Baz!
304
305 This is not just a performance thing.  Suppose we have
306         data Foo.S = MkS Baz.T
307         data Baz.T = MkT Foo.S
308 (in different interface files, of course).
309 Now, first we load and typecheck Foo.S, and add it to the type envt.  
310 If we do explore MkS's argument, we'll load and typecheck Baz.T.
311 If we explore MkT's argument we'll find Foo.S already in the envt.  
312
313 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
314 typecheck the type Baz.T.  So we'd fault in Baz.T... and then need Foo.S...
315 which isn't done yet.
316
317 All very cunning. However, there is a rather subtle gotcha which bit
318 me when developing this stuff.  When we typecheck the decl for S, we
319 extend the type envt with S, MkS, and all its implicit Ids.  Suppose
320 (a bug, but it happened) that the list of implicit Ids depended in
321 turn on the constructor arg types.  Then the following sequence of
322 events takes place:
323         * we build a thunk <t> for the constructor arg tys
324         * we build a thunk for the extended type environment (depends on <t>)
325         * we write the extended type envt into the global EPS mutvar
326         
327 Now we look something up in the type envt
328         * that pulls on <t>
329         * which reads the global type envt out of the global EPS mutvar
330         * but that depends in turn on <t>
331
332 It's subtle, because, it'd work fine if we typechecked the constructor args 
333 eagerly -- they don't need the extended type envt.  They just get the extended
334 type envt by accident, because they look at it later.
335
336 What this means is that the implicitTyThings MUST NOT DEPEND on any of
337 the forkM stuff.
338
339
340 \begin{code}
341 tcIfaceDecl :: IfaceDecl -> IfL TyThing
342
343 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
344   = do  { name <- lookupIfaceTop occ_name
345         ; ty <- tcIfaceType iface_type
346         ; info <- tcIdInfo name ty info
347         ; return (AnId (mkVanillaGlobal name ty info)) }
348
349 tcIfaceDecl (IfaceData {ifName = occ_name, 
350                         ifTyVars = tv_bndrs, ifCtxt = rdr_ctxt,
351                         ifCons = rdr_cons, 
352                         ifVrcs = arg_vrcs, ifRec = is_rec, 
353                         ifGeneric = want_generic })
354   = do  { tc_name <- lookupIfaceTop occ_name
355         ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
356
357         { traceIf (text "tcIfaceDecl" <+> ppr rdr_ctxt)
358
359         ; ctxt <- forkM (ptext SLIT("Ctxt of data decl") <+> ppr tc_name) $
360                      tcIfaceCtxt rdr_ctxt
361                 -- The reason for laziness here is to postpone
362                 -- looking at the context, because the class may not
363                 -- be in the type envt yet.  E.g. 
364                 --      class Real a where { toRat :: a -> Ratio Integer }
365                 --      data (Real a) => Ratio a = ...
366                 -- We suck in the decl for Real, and type check it, which sucks
367                 -- in the data type Ratio; but we must postpone typechecking the
368                 -- context
369
370         ; tycon <- fixM ( \ tycon -> do
371             { cons <- tcIfaceDataCons tycon tyvars ctxt rdr_cons
372             ; tycon <- buildAlgTyCon tc_name tyvars ctxt cons 
373                             arg_vrcs is_rec want_generic
374             ; return tycon
375             })
376         ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
377         ; return (ATyCon tycon)
378     } }
379
380 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs, 
381                        ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
382    = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
383      { tc_name <- lookupIfaceTop occ_name
384      ; rhs_ty <- tcIfaceType rdr_rhs_ty
385      ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
386      }
387
388 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs, 
389                          ifFDs = rdr_fds, ifSigs = rdr_sigs, 
390                          ifVrcs = tc_vrcs, ifRec = tc_isrec })
391   = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
392     { cls_name <- lookupIfaceTop occ_name
393     ; ctxt <- tcIfaceCtxt rdr_ctxt
394     ; sigs <- mappM tc_sig rdr_sigs
395     ; fds  <- mappM tc_fd rdr_fds
396     ; cls  <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
397     ; return (AClass cls) }
398   where
399    tc_sig (IfaceClassOp occ dm rdr_ty)
400      = do { op_name <- lookupIfaceTop occ
401           ; op_ty   <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
402                 -- Must be done lazily for just the same reason as the 
403                 -- context of a data decl: the type sig might mention the
404                 -- class being defined
405           ; return (op_name, dm, op_ty) }
406
407    mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
408
409    tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
410                            ; tvs2' <- mappM tcIfaceTyVar tvs2
411                            ; return (tvs1', tvs2') }
412
413 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
414   = do  { name <- lookupIfaceTop rdr_name
415         ; return (ATyCon (mkForeignTyCon name ext_name 
416                                          liftedTypeKind 0 [])) }
417
418 tcIfaceDataCons tycon tyvars ctxt if_cons
419   = case if_cons of
420         IfAbstractTyCon  -> return mkAbstractTyConRhs
421         IfDataTyCon cons -> do  { data_cons <- mappM tc_con_decl cons
422                                 ; return (mkDataTyConRhs data_cons) }
423         IfNewTyCon con   -> do  { data_con <- tc_con_decl con
424                                 ; return (mkNewTyConRhs data_con) }
425   where
426     tc_con_decl (IfaceConDecl occ ex_tvs ex_ctxt args stricts field_lbls)
427       = bindIfaceTyVars ex_tvs  $ \ ex_tyvars -> do
428         { name <- lookupIfaceTop occ
429         ; ex_theta <- tcIfaceCtxt ex_ctxt       -- Laziness seems not worth the bother here
430
431         -- Read the argument types, but lazily to avoid faulting in
432         -- the component types unless they are really needed
433         ; arg_tys <- forkM (mk_doc name args) (mappM tcIfaceType args) ;
434
435         ; lbl_names <- mappM lookupIfaceTop field_lbls
436
437         ; buildDataCon name stricts lbl_names
438                        tyvars ctxt ex_tyvars ex_theta 
439                        arg_tys tycon
440         }
441     mk_doc con_name args = ptext SLIT("Constructor") <+> sep [ppr con_name, ppr args]
442 \end{code}      
443
444
445 %************************************************************************
446 %*                                                                      *
447                 Instances
448 %*                                                                      *
449 %************************************************************************
450
451 The gating story for instance declarations
452 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
453 When we are looking for a dict (C t1..tn), we slurp in instance decls for
454 C that 
455         mention at least one of the type constructors 
456         at the roots of t1..tn
457
458 Why "at least one" rather than "all"?  Because functional dependencies 
459 complicate the picture.  Consider
460         class C a b | a->b where ...
461         instance C Foo Baz where ...
462 Here, the gates are really only C and Foo, *not* Baz.
463 That is, if C and Foo are visible, even if Baz isn't, we must
464 slurp the decl, even if Baz is thus far completely unknown to the
465 system.
466
467 Why "roots of the types"?  Reason is overlap.  For example, suppose there 
468 are interfaces in the pool for
469   (a)   C Int b
470  (b)    C a [b]
471   (c)   C a [T] 
472 Then, if we are trying to resolve (C Int x), we need (a)
473 if we are trying to resolve (C x [y]), we need *both* (b) and (c),
474 even though T is not involved yet, so that we spot the overlap.
475
476
477 NOTE: if you use an instance decl with NO type constructors
478         instance C a where ...
479 and look up an Inst that only has type variables such as (C (n o))
480 then GHC won't necessarily suck in the instances that overlap with this.
481
482
483 \begin{code}
484 loadImportedInsts :: Class -> [Type] -> TcM PackageInstEnv
485 loadImportedInsts cls tys
486   = do  {       -- Get interfaces for wired-in things, such as Integer
487                 -- Any non-wired-in tycons will already be loaded, else
488                 -- we couldn't have them in the Type
489         ; this_mod <- getModule 
490         ; let { (cls_gate, tc_gates) = predInstGates cls tys
491               ; imp_wi n = isWiredInName n && this_mod /= nameModule n
492               ; wired_tcs = filter imp_wi tc_gates }
493                         -- Wired-in tycons not from this module.  The "this-module"
494                         -- test bites only when compiling Base etc, because loadHomeInterface
495                         -- barfs if it's asked to load a non-existent interface
496         ; if null wired_tcs then returnM ()
497           else initIfaceTcRn (mapM_ (loadHomeInterface wired_doc) wired_tcs)
498
499         ; eps_var <- getEpsVar
500         ; eps <- readMutVar eps_var
501
502         -- For interest: report the no-type-constructor case.
503         -- Don't report when -fallow-undecidable-instances is on, because then
504         -- we call loadImportedInsts when looking up even predicates like (C a)
505         -- But without undecidable instances it's rare to see C (a b) and 
506         -- somethat interesting
507 {- (comment out; happens a lot in some code)
508 #ifdef DEBUG
509         ; dflags  <- getDOpts
510         ; WARN( not (dopt Opt_AllowUndecidableInstances dflags) && null tc_gates, 
511                 ptext SLIT("Interesting! No tycons in Inst:") 
512                         <+> pprClassPred cls tys )
513           return ()
514 #endif
515 -}
516         -- Suck in the instances
517         ; let { (inst_pool', iface_insts) 
518                     = selectInsts (eps_insts eps) cls_gate tc_gates }
519
520         -- Empty => finish up rapidly, without writing to eps
521         ; if null iface_insts then
522                 return (eps_inst_env eps)
523           else do
524         { writeMutVar eps_var (eps {eps_insts = inst_pool'})
525
526         ; traceIf (sep [ptext SLIT("Importing instances for") <+> pprClassPred cls tys, 
527                         nest 2 (vcat (map ppr iface_insts))])
528
529         -- Typecheck the new instances
530         ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
531
532         -- And put them in the package instance environment
533         ; updateEps ( \ eps ->
534             let 
535                 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
536             in
537             (eps { eps_inst_env = inst_env' }, inst_env')
538         )}}
539   where
540     wired_doc = ptext SLIT("Need home inteface for wired-in thing")
541
542 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
543
544 tcIfaceInst :: IfaceInst -> IfL DFunId
545 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
546   = tcIfaceExtId (LocalTop dfun_occ)
547
548 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
549 selectInsts pool@(Pool insts n_in n_out) cls tycons
550   = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
551   where
552     (insts', iface_insts) 
553         = case lookupNameEnv insts cls of {
554                 Nothing -> (insts, []) ;
555                 Just gated_insts ->
556         
557           case choose1 gated_insts  of {
558             (_, []) -> (insts, []) ;    -- None picked
559             (gated_insts', iface_insts') -> 
560
561           (extendNameEnv insts cls gated_insts', iface_insts') }}
562
563     choose1 gated_insts
564         | null tycons                   -- Bizarre special case of C (a b); then there are no tycons
565         = ([], map snd gated_insts)     -- Just grab all the instances, no real alternative
566         | otherwise                     -- Normal case
567         = foldl choose2 ([],[]) gated_insts
568
569         -- Reverses the gated decls, but that doesn't matter
570     choose2 (gis, decls) (gates, decl)
571         |  null gates   -- Happens when we have 'instance T a where ...'
572         || any (`elem` tycons) gates = (gis,               decl:decls)
573         | otherwise                  = ((gates,decl) : gis, decls)
574 \end{code}
575
576 %************************************************************************
577 %*                                                                      *
578                 Rules
579 %*                                                                      *
580 %************************************************************************
581
582 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
583 are in the type environment.  However, remember that typechecking a Rule may 
584 (as a side effect) augment the type envt, and so we may need to iterate the process.
585
586 \begin{code}
587 loadImportedRules :: HscEnv -> ModGuts -> IO PackageRuleBase
588 loadImportedRules hsc_env guts
589   = initIfaceRules hsc_env guts $ do 
590         { -- Get new rules
591           if_rules <- updateEps (\ eps ->
592                 let { (new_pool, if_rules) = selectRules (eps_rules eps) (eps_PTE eps) }
593                 in (eps { eps_rules = new_pool }, if_rules) )
594
595         ; traceIf (ptext SLIT("Importing rules:") <+> vcat (map ppr if_rules))
596
597         ; let tc_rule (mod, rule) = initIfaceLcl mod (tcIfaceRule rule)
598         ; core_rules <- mapM tc_rule if_rules
599
600         -- Debug print
601         ; traceIf (ptext SLIT("Imported rules:") <+> pprIdRules core_rules)
602         
603         -- Update the rule base and return it
604         ; updateEps (\ eps -> 
605             let { new_rule_base = extendRuleBaseList (eps_rule_base eps) core_rules }
606             in (eps { eps_rule_base = new_rule_base }, new_rule_base)
607           ) 
608
609         -- Strictly speaking, at this point we should go round again, since
610         -- typechecking one set of rules may bring in new things which enable
611         -- some more rules to come in.  But we call loadImportedRules several
612         -- times anyway, so I'm going to be lazy and ignore this.
613     }
614
615
616 selectRules :: RulePool -> TypeEnv -> (RulePool, [(ModuleName, IfaceRule)])
617 -- Not terribly efficient.  Look at each rule in the pool to see if
618 -- all its gates are in the type env.  If so, take it out of the pool.
619 -- If not, trim its gates for next time.
620 selectRules (Pool rules n_in n_out) type_env
621   = (Pool rules' n_in (n_out + length if_rules), if_rules)
622   where
623     (rules', if_rules) = foldl do_one ([], []) rules
624
625     do_one (pool, if_rules) (gates, rule)
626         | null gates' = (pool, rule:if_rules)
627         | otherwise   = ((gates',rule) : pool, if_rules)
628         where
629           gates' = filter (not . (`elemNameEnv` type_env)) gates
630
631
632 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
633 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
634                         ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
635   = bindIfaceBndrs bndrs        $ \ bndrs' ->
636     do  { fn <- tcIfaceExtId fn_rdr
637         ; args' <- mappM tcIfaceExpr args
638         ; rhs'  <- tcIfaceExpr rhs
639         ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
640
641 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
642   = do  { fn <- tcIfaceExtId fn_rdr
643         ; returnM (fn, core_rule) }
644 \end{code}
645
646
647 %************************************************************************
648 %*                                                                      *
649                         Types
650 %*                                                                      *
651 %************************************************************************
652
653 \begin{code}
654 tcIfaceType :: IfaceType -> IfL Type
655 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
656 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
657 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
658 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
659 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
660 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
661
662 tcIfaceTypes tys = mapM tcIfaceType tys
663
664 -----------------------------------------
665 tcIfacePredType :: IfacePredType -> IfL PredType
666 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
667 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
668
669 -----------------------------------------
670 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
671 tcIfaceCtxt sts = mappM tcIfacePredType sts
672 \end{code}
673
674
675 %************************************************************************
676 %*                                                                      *
677                         Core
678 %*                                                                      *
679 %************************************************************************
680
681 \begin{code}
682 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
683 tcIfaceExpr (IfaceType ty)
684   = tcIfaceType ty              `thenM` \ ty' ->
685     returnM (Type ty')
686
687 tcIfaceExpr (IfaceLcl name)
688   = tcIfaceLclId name   `thenM` \ id ->
689     returnM (Var id)
690
691 tcIfaceExpr (IfaceExt gbl)
692   = tcIfaceExtId gbl    `thenM` \ id ->
693     returnM (Var id)
694
695 tcIfaceExpr (IfaceLit lit)
696   = returnM (Lit lit)
697
698 tcIfaceExpr (IfaceFCall cc ty)
699   = tcIfaceType ty      `thenM` \ ty' ->
700     newUnique           `thenM` \ u ->
701     returnM (Var (mkFCallId u cc ty'))
702
703 tcIfaceExpr (IfaceTuple boxity args) 
704   = mappM tcIfaceExpr args      `thenM` \ args' ->
705     let
706         -- Put the missing type arguments back in
707         con_args = map (Type . exprType) args' ++ args'
708     in
709     returnM (mkApps (Var con_id) con_args)
710   where
711     arity = length args
712     con_id = dataConWorkId (tupleCon boxity arity)
713     
714
715 tcIfaceExpr (IfaceLam bndr body)
716   = bindIfaceBndr bndr          $ \ bndr' ->
717     tcIfaceExpr body            `thenM` \ body' ->
718     returnM (Lam bndr' body')
719
720 tcIfaceExpr (IfaceApp fun arg)
721   = tcIfaceExpr fun             `thenM` \ fun' ->
722     tcIfaceExpr arg             `thenM` \ arg' ->
723     returnM (App fun' arg')
724
725 tcIfaceExpr (IfaceCase scrut case_bndr alts) 
726   = tcIfaceExpr scrut           `thenM` \ scrut' ->
727     newIfaceName case_bndr      `thenM` \ case_bndr_name ->
728     let
729         scrut_ty   = exprType scrut'
730         case_bndr' = mkLocalId case_bndr_name scrut_ty
731         tc_app     = splitTyConApp scrut_ty
732                 -- NB: Won't always succeed (polymoprhic case)
733                 --     but won't be demanded in those cases
734                 -- NB: not tcSplitTyConApp; we are looking at Core here
735                 --     look through non-rec newtypes to find the tycon that
736                 --     corresponds to the datacon in this case alternative
737     in
738     extendIfaceIdEnv [case_bndr']       $
739     mappM (tcIfaceAlt tc_app) alts      `thenM` \ alts' ->
740     returnM (Case scrut' case_bndr' alts')
741
742 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
743   = tcIfaceExpr rhs             `thenM` \ rhs' ->
744     bindIfaceId bndr            $ \ bndr' ->
745     tcIfaceExpr body            `thenM` \ body' ->
746     returnM (Let (NonRec bndr' rhs') body')
747
748 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
749   = bindIfaceIds bndrs          $ \ bndrs' ->
750     mappM tcIfaceExpr rhss      `thenM` \ rhss' ->
751     tcIfaceExpr body            `thenM` \ body' ->
752     returnM (Let (Rec (bndrs' `zip` rhss')) body')
753   where
754     (bndrs, rhss) = unzip pairs
755
756 tcIfaceExpr (IfaceNote note expr) 
757   = tcIfaceExpr expr            `thenM` \ expr' ->
758     case note of
759         IfaceCoerce to_ty -> tcIfaceType to_ty  `thenM` \ to_ty' ->
760                              returnM (Note (Coerce to_ty'
761                                                    (exprType expr')) expr')
762         IfaceInlineCall   -> returnM (Note InlineCall expr')
763         IfaceInlineMe     -> returnM (Note InlineMe   expr')
764         IfaceSCC cc       -> returnM (Note (SCC cc)   expr')
765         IfaceCoreNote n   -> returnM (Note (CoreNote n) expr')
766
767 -------------------------
768 tcIfaceAlt _ (IfaceDefault, names, rhs)
769   = ASSERT( null names )
770     tcIfaceExpr rhs             `thenM` \ rhs' ->
771     returnM (DEFAULT, [], rhs')
772   
773 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
774   = ASSERT( null names )
775     tcIfaceExpr rhs             `thenM` \ rhs' ->
776     returnM (LitAlt lit, [], rhs')
777
778 -- A case alternative is made quite a bit more complicated
779 -- by the fact that we omit type annotations because we can
780 -- work them out.  True enough, but its not that easy!
781 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
782   = let 
783         tycon_mod = nameModuleName (tyConName tycon)
784     in
785     tcIfaceDataCon (ExtPkg tycon_mod data_occ)  `thenM` \ con ->
786     newIfaceNames arg_occs                      `thenM` \ arg_names ->
787     let
788         ex_tyvars   = dataConExistentialTyVars con
789         main_tyvars = tyConTyVars tycon
790         ex_tyvars'  = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars] 
791         ex_tys'     = mkTyVarTys ex_tyvars'
792         arg_tys     = dataConArgTys con (inst_tys ++ ex_tys')
793         id_names    = dropList ex_tyvars arg_names
794         arg_ids
795 #ifdef DEBUG
796                 | not (equalLength id_names arg_tys)
797                 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
798                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
799                                          ppr arg_tys)
800                 | otherwise
801 #endif
802                 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
803     in
804     ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
805              ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$  ppr main_tyvars  )
806     extendIfaceTyVarEnv ex_tyvars'      $
807     extendIfaceIdEnv arg_ids            $
808     tcIfaceExpr rhs                     `thenM` \ rhs' ->
809     returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
810
811 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
812   = newIfaceNames arg_occs      `thenM` \ arg_names ->
813     let
814         [con]   = tyConDataCons tycon
815         arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
816     in
817     ASSERT( isTupleTyCon tycon )
818     extendIfaceIdEnv arg_ids            $
819     tcIfaceExpr rhs                     `thenM` \ rhs' ->
820     returnM (DataAlt con, arg_ids, rhs')
821 \end{code}
822
823
824 \begin{code}
825 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
826 tcExtCoreBindings mod []     = return []
827 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
828
829 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
830 do_one mod (IfaceNonRec bndr rhs) thing_inside
831   = do  { rhs' <- tcIfaceExpr rhs
832         ; bndr' <- newExtCoreBndr mod bndr
833         ; extendIfaceIdEnv [bndr'] $ do 
834         { core_binds <- thing_inside
835         ; return (NonRec bndr' rhs' : core_binds) }}
836
837 do_one mod (IfaceRec pairs) thing_inside
838   = do  { bndrs' <- mappM (newExtCoreBndr mod) bndrs
839         ; extendIfaceIdEnv bndrs' $ do
840         { rhss' <- mappM tcIfaceExpr rhss
841         ; core_binds <- thing_inside
842         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
843   where
844     (bndrs,rhss) = unzip pairs
845 \end{code}
846
847
848 %************************************************************************
849 %*                                                                      *
850                 IdInfo
851 %*                                                                      *
852 %************************************************************************
853
854 \begin{code}
855 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
856 tcIdInfo name ty NoInfo         = return vanillaIdInfo
857 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
858   where
859     -- Set the CgInfo to something sensible but uninformative before
860     -- we start; default assumption is that it has CAFs
861     init_info = vanillaIdInfo
862
863     tcPrag info HsNoCafRefs         = returnM (info `setCafInfo`   NoCafRefs)
864     tcPrag info (HsArity arity)     = returnM (info `setArityInfo` arity)
865     tcPrag info (HsStrictness str)  = returnM (info `setAllStrictnessInfo` Just str)
866
867         -- The next two are lazy, so they don't transitively suck stuff in
868     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
869     tcPrag info (HsUnfold inline_prag expr)
870         = tcPragExpr name expr  `thenM` \ maybe_expr' ->
871           let
872                 -- maybe_expr' doesn't get looked at if the unfolding
873                 -- is never inspected; so the typecheck doesn't even happen
874                 unfold_info = case maybe_expr' of
875                                 Nothing    -> noUnfolding
876                                 Just expr' -> mkTopUnfolding expr' 
877           in
878           returnM (info `setUnfoldingInfoLazily` unfold_info
879                         `setInlinePragInfo`      inline_prag)
880 \end{code}
881
882 \begin{code}
883 tcWorkerInfo ty info wkr_name arity
884   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
885
886         -- We return without testing maybe_wkr_id, but as soon as info is
887         -- looked at we will test it.  That's ok, because its outside the
888         -- knot; and there seems no big reason to further defer the
889         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
890         -- over the unfolding until it's actually used does seem worth while.)
891         ; us <- newUniqueSupply
892
893         ; returnM (case mb_wkr_id of
894                      Nothing     -> info
895                      Just wkr_id -> add_wkr_info us wkr_id info) }
896   where
897     doc = text "Worker for" <+> ppr wkr_name
898     add_wkr_info us wkr_id info
899         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
900                `setWorkerInfo`           HasWorker wkr_id arity
901
902     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
903
904         -- We are relying here on strictness info always appearing 
905         -- before worker info,  fingers crossed ....
906     strict_sig = case newStrictnessInfo info of
907                    Just sig -> sig
908                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
909 \end{code}
910
911 For unfoldings we try to do the job lazily, so that we never type check
912 an unfolding that isn't going to be looked at.
913
914 \begin{code}
915 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
916 tcPragExpr name expr
917   = forkM_maybe doc $
918     tcIfaceExpr expr            `thenM` \ core_expr' ->
919
920                 -- Check for type consistency in the unfolding
921     ifOptM Opt_DoCoreLinting (
922         get_in_scope_ids                        `thenM` \ in_scope -> 
923         case lintUnfolding noSrcLoc in_scope core_expr' of
924           Nothing       -> returnM ()
925           Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
926     )                           `thenM_`
927
928    returnM core_expr'   
929   where
930     doc = text "Unfolding of" <+> ppr name
931     get_in_scope_ids    -- Urgh; but just for linting
932         = setLclEnv () $ 
933           do    { env <- getGblEnv 
934                 ; case if_rec_types env of {
935                           Nothing -> return [] ;
936                           Just (_, get_env) -> do
937                 { type_env <- get_env
938                 ; return (typeEnvIds type_env) }}}
939 \end{code}
940
941
942
943 %************************************************************************
944 %*                                                                      *
945                 Bindings
946 %*                                                                      *
947 %************************************************************************
948
949 \begin{code}
950 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
951 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
952   = bindIfaceId bndr thing_inside
953 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
954   = bindIfaceTyVar bndr thing_inside
955     
956 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
957 bindIfaceBndrs []     thing_inside = thing_inside []
958 bindIfaceBndrs (b:bs) thing_inside
959   = bindIfaceBndr b     $ \ b' ->
960     bindIfaceBndrs bs   $ \ bs' ->
961     thing_inside (b':bs')
962
963 -----------------------
964 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
965 bindIfaceId (occ, ty) thing_inside
966   = do  { name <- newIfaceName occ
967         ; ty' <- tcIfaceType ty
968         ; let { id = mkLocalId name ty' }
969         ; extendIfaceIdEnv [id] (thing_inside id) }
970     
971 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
972 bindIfaceIds bndrs thing_inside
973   = do  { names <- newIfaceNames occs
974         ; tys' <- mappM tcIfaceType tys
975         ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
976         ; extendIfaceIdEnv ids (thing_inside ids) }
977   where
978     (occs,tys) = unzip bndrs
979
980
981 -----------------------
982 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
983 newExtCoreBndr mod (occ, ty)
984   = do  { name <- newGlobalBinder mod occ 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 occ
992         ; let 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 occs
998         ; let tyvars = zipWith mk_iface_tyvar names kinds
999         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1000   where
1001     (occs,kinds) = unzip bndrs
1002
1003 mk_iface_tyvar name kind = mkTyVar name kind
1004 \end{code}