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