[project @ 2003-10-10 07:34:34 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         tcIfaceKind, loadImportedInsts, 
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             ( Kind, openTypeKind, liftedTypeKind, 
24                           unliftedTypeKind, mkArrowKind, splitTyConApp, 
25                           mkTyVarTys, mkGenTyConApp, mkTyVarTys, ThetaType )
26 import TypeRep          ( Type(..), PredType(..) )
27 import TyCon            ( TyCon, tyConName )
28 import HscTypes         ( ExternalPackageState(..), PackageInstEnv,
29                           TyThing(..), implicitTyThings, typeEnvIds,
30                           ModIface(..), ModDetails(..), InstPool, 
31                           TypeEnv, mkTypeEnv, extendTypeEnvList, lookupTypeEnv,
32                           DeclPool, RulePool, Pool(..), Gated, addRuleToPool )
33 import InstEnv          ( extendInstEnv )
34 import CoreSyn
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 )
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 )
61 import Maybes           ( expectJust )
62 import CmdLineOpts      ( DynFlag(..) )
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, iface_rules) <- 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                 ; (new_rules, iface_rules) = selectRules (eps_rules eps) 
168                                                          (map getName new_things)
169                                                          new_type_env }
170             in (eps { eps_PTE = new_type_env, eps_rules = new_rules }, 
171                 (new_things, iface_rules))
172           )
173
174     -- Now type-check those rules (which may side-effect the EPS again)
175         ; traceIf (text "tcImport: extend type env" <+> ppr new_things)
176         ; traceIf (text "tcImport: rules" <+> vcat (map ppr iface_rules))
177         ; core_rules <- mapM tc_rule iface_rules
178         ; updateEps_ (\ eps -> 
179             eps { eps_rule_base = extendRuleBaseList (eps_rule_base eps) core_rules }
180           ) }
181         
182 tc_rule (mod, rule) = initIfaceLcl mod (tcIfaceRule rule)
183
184 getThing :: Name -> IfG TyThing
185 -- Find and typecheck the thing; the Name might be a "subordinate name"
186 -- of the "main thing" (e.g. the constructor of a data type declaration)
187 -- The Thing we return is the parent "main thing"
188
189 getThing name
190   | Just thing <- wiredInNameTyThing_maybe name
191    = return thing
192
193   | otherwise = do      -- The normal case, not wired in
194   {     -- Get the decl from the pool
195     decl <- updateEps (\ eps ->
196             let 
197                 (decls', decl) = selectDecl (eps_decls eps) name
198             in
199             (eps { eps_decls = decls' }, decl))
200
201     -- Typecheck it
202     -- Side-effects EPS by faulting in any needed decls
203     -- (via nested calls to tcImportDecl)
204   ; initIfaceLcl (nameModuleName name) (tcIfaceDecl decl) }
205
206
207 selectDecl :: DeclPool -> Name -> (DeclPool, IfaceDecl)
208 -- Use nameParent to get the parent name of the thing
209 selectDecl (Pool decls_map n_in n_out) name
210    = (Pool decls' n_in (n_out+1), decl)
211    where
212      main_name = nameParent name
213      decl = case lookupNameEnv decls_map main_name of
214                 Nothing   -> pprPanic "selectDecl" (ppr main_name <+> ppr name) ;
215                 Just decl -> decl
216
217      decls' = delFromNameEnv decls_map main_name
218 \end{code}
219
220 %************************************************************************
221 %*                                                                      *
222                 Other interfaces
223 %*                                                                      *
224 %************************************************************************
225
226 \begin{code}
227 typecheckIface :: ModIface -> IfG ModDetails
228 -- Used when we decide not to recompile, but intead to use the
229 -- interface to construct the type environment for the module
230 typecheckIface iface
231   = initIfaceLcl (moduleName (mi_module iface)) $
232     do  { ty_things <- mapM (tcIfaceDecl . snd) (mi_decls iface)
233         ; rules <- mapM tcIfaceRule (mi_rules iface)
234         ; dfuns <- mapM tcIfaceInst (mi_insts iface)
235         ; return (ModDetails { md_types = mkTypeEnv ty_things,
236                                md_insts = dfuns,
237                                md_rules = rules }) }
238 \end{code}
239
240
241 %************************************************************************
242 %*                                                                      *
243                 Type and class declarations
244 %*                                                                      *
245 %************************************************************************
246
247 When typechecking a data type decl, we *lazily* (via forkM) typecheck
248 the constructor argument types.  This is in the hope that we may never
249 poke on those argument types, and hence may never need to load the
250 interface files for types mentioned in the arg types.
251
252 E.g.    
253         data Foo.S = MkS Baz.T
254 Mabye we can get away without even loading the interface for Baz!
255
256 This is not just a performance thing.  Suppose we have
257         data Foo.S = MkS Baz.T
258         data Baz.T = MkT Foo.S
259 (in different interface files, of course).
260 Now, first we load and typecheck Foo.S, and add it to the type envt.  
261 If we do explore MkS's argument, we'll load and typecheck Baz.T.
262 If we explore MkT's argument we'll find Foo.S already in the envt.  
263
264 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
265 typecheck the type Baz.T.  So we'd fault in Baz.T... and then need Foo.S...
266 which isn't done yet.
267
268 All very cunning. However, there is a rather subtle gotcha which bit
269 me when developing this stuff.  When we typecheck the decl for S, we
270 extend the type envt with S, MkS, and all its implicit Ids.  Suppose
271 (a bug, but it happened) that the list of implicit Ids depended in
272 turn on the constructor arg types.  Then the following sequence of
273 events takes place:
274         * we build a thunk <t> for the constructor arg tys
275         * we build a thunk for the extended type environment (depends on <t>)
276         * we write the extended type envt into the global EPS mutvar
277         
278 Now we look something up in the type envt
279         * that pulls on <t>
280         * which reads the global type envt out of the global EPS mutvar
281         * but that depends in turn on <t>
282
283 It's subtle, because, it'd work fine if we typechecked the constructor args 
284 eagerly -- they don't need the extended type envt.  They just get the extended
285 type envt by accident, because they look at it later.
286
287 What this means is that the implicitTyThings MUST NOT DEPEND on any of
288 the forkM stuff.
289
290
291 \begin{code}
292 tcIfaceDecl :: IfaceDecl -> IfL TyThing
293
294 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
295   = do  { name <- lookupIfaceTop occ_name
296         ; ty <- tcIfaceType iface_type
297         ; info <- tcIdInfo name ty info
298         ; return (AnId (mkVanillaGlobal name ty info)) }
299
300 tcIfaceDecl (IfaceData {ifND = new_or_data, ifName = occ_name, 
301                         ifTyVars = tv_bndrs, ifCtxt = rdr_ctxt,
302                         ifCons = rdr_cons, 
303                         ifVrcs = arg_vrcs, ifRec = is_rec, 
304                         ifGeneric = want_generic })
305   = do  { tc_name <- lookupIfaceTop occ_name
306         ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
307
308         { traceIf (text "tcIfaceDecl" <+> ppr rdr_ctxt)
309
310         ; ctxt <- forkM (ptext SLIT("Ctxt of data decl") <+> ppr tc_name) $
311                      tcIfaceCtxt rdr_ctxt
312                 -- The reason for laziness here is to postpone
313                 -- looking at the context, because the class may not
314                 -- be in the type envt yet.  E.g. 
315                 --      class Real a where { toRat :: a -> Ratio Integer }
316                 --      data (Real a) => Ratio a = ...
317                 -- We suck in the decl for Real, and type check it, which sucks
318                 -- in the data type Ratio; but we must postpone typechecking the
319                 -- context
320
321         ; tycon <- fixM ( \ tycon -> do
322             { cons <- tcIfaceDataCons tycon tyvars ctxt rdr_cons
323             ; tycon <- buildAlgTyCon new_or_data tc_name tyvars ctxt cons 
324                             arg_vrcs is_rec want_generic
325             ; return tycon
326             })
327         ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
328         ; return (ATyCon tycon)
329     } }
330
331 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs, 
332                        ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
333    = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
334      { tc_name <- lookupIfaceTop occ_name
335      ; rhs_ty <- tcIfaceType rdr_rhs_ty
336      ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
337      }
338
339 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs, 
340                          ifFDs = rdr_fds, ifSigs = rdr_sigs, 
341                          ifVrcs = tc_vrcs, ifRec = tc_isrec })
342   = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
343     { cls_name <- lookupIfaceTop occ_name
344     ; ctxt <- tcIfaceCtxt rdr_ctxt
345     ; sigs <- mappM tc_sig rdr_sigs
346     ; fds  <- mappM tc_fd rdr_fds
347     ; cls  <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
348     ; return (AClass cls) }
349   where
350    tc_sig (IfaceClassOp occ dm rdr_ty)
351      = do { op_name <- lookupIfaceTop occ
352           ; op_ty   <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
353                 -- Must be done lazily for just the same reason as the 
354                 -- context of a data decl: the type sig might mention the
355                 -- class being defined
356           ; return (op_name, dm, op_ty) }
357
358    mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
359
360    tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
361                            ; tvs2' <- mappM tcIfaceTyVar tvs2
362                            ; return (tvs1', tvs2') }
363
364 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
365   = do  { name <- lookupIfaceTop rdr_name
366         ; return (ATyCon (mkForeignTyCon name ext_name 
367                                          liftedTypeKind 0 [])) }
368
369 tcIfaceDataCons tycon tyvars ctxt Unknown
370   = returnM Unknown
371
372 tcIfaceDataCons tycon tyvars ctxt (DataCons cs)
373   = mappM tc_con_decl cs        `thenM` \ data_cons ->
374     returnM (DataCons data_cons)
375   where
376     tc_con_decl (IfaceConDecl occ ex_tvs ex_ctxt args stricts field_lbls)
377       = bindIfaceTyVars ex_tvs  $ \ ex_tyvars -> do
378         { name <- lookupIfaceTop occ
379         ; ex_theta <- tcIfaceCtxt ex_ctxt       -- Laziness seems not worth the bother here
380
381         -- Read the argument types, but lazily to avoid faulting in
382         -- the component types unless they are really needed
383         ; arg_tys <- forkM (mk_doc name args) (mappM tcIfaceType args) ;
384
385         ; lbl_names <- mappM lookupIfaceTop field_lbls
386
387         ; buildDataCon name stricts lbl_names
388                        tyvars ctxt ex_tyvars ex_theta 
389                        arg_tys tycon
390         }
391     mk_doc con_name args = ptext SLIT("Constructor") <+> sep [ppr con_name, ppr args]
392 \end{code}      
393
394
395 %************************************************************************
396 %*                                                                      *
397                 Instances
398 %*                                                                      *
399 %************************************************************************
400
401 The gating story for instance declarations
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
403 When we are looking for a dict (C t1..tn), we slurp in instance decls for
404 C that 
405         mention at least one of the type constructors 
406         at the roots of t1..tn
407
408 Why "at least one" rather than "all"?  Because functional dependencies 
409 complicate the picture.  Consider
410         class C a b | a->b where ...
411         instance C Foo Baz where ...
412 Here, the gates are really only C and Foo, *not* Baz.
413 That is, if C and Foo are visible, even if Baz isn't, we must
414 slurp the decl, even if Baz is thus far completely unknown to the
415 system.
416
417 Why "roots of the types"?  Reason is overlap.  For example, suppose there 
418 are interfaces in the pool for
419   (a)   C Int b
420  (b)    C a [b]
421   (c)   C a [T] 
422 Then, if we are trying to resolve (C Int x), we need (a)
423 if we are trying to resolve (C x [y]), we need *both* (b) and (c),
424 even though T is not involved yet, so that we spot the overlap.
425
426 \begin{code}
427 loadImportedInsts :: Class -> [Type] -> TcM PackageInstEnv
428 loadImportedInsts cls tys
429   = do  {       -- Get interfaces for wired-in things, such as Integer
430                 -- Any non-wired-in tycons will already be loaded, else
431                 -- we couldn't have them in the Type
432         ; this_mod <- getModule 
433         ; let { (cls_gate, tc_gates) = predInstGates cls tys
434               ; imp_wi n = isWiredInName n && this_mod /= nameModule n
435               ; wired_tcs = filter imp_wi tc_gates }
436                         -- Wired-in tycons not from this module.  The "this-module"
437                         -- test bites only when compiling Base etc, because loadHomeInterface
438                         -- barfs if it's asked to load a non-existent interface
439         ; if null wired_tcs then returnM ()
440           else initIfaceTcRn (mapM_ (loadHomeInterface wired_doc) wired_tcs)
441
442         ; eps_var <- getEpsVar
443         ; eps <- readMutVar eps_var
444
445         -- Suck in the instances
446         ; let { (inst_pool', iface_insts) 
447                     = selectInsts (eps_insts eps) cls_gate tc_gates }
448
449         -- Empty => finish up rapidly, without writing to eps
450         ; if null iface_insts then
451                 return (eps_inst_env eps)
452           else do
453         { writeMutVar eps_var (eps {eps_insts = inst_pool'})
454
455         -- Typecheck the new instances
456         ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
457
458         -- And put them in the package instance environment
459         ; updateEps ( \ eps ->
460             let 
461                 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
462             in
463             (eps { eps_inst_env = inst_env' }, inst_env')
464         )}}
465   where
466     wired_doc = ptext SLIT("Need home inteface for wired-in thing")
467
468 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
469
470 tcIfaceInst :: IfaceInst -> IfL DFunId
471 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
472   = tcIfaceExtId (LocalTop dfun_occ)
473
474 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
475 selectInsts pool@(Pool insts n_in n_out) cls tycons
476   = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
477   where
478     (insts', iface_insts) 
479         = case lookupNameEnv insts cls of {
480                 Nothing -> (insts, []) ;
481                 Just gated_insts -> 
482         
483           case foldl choose ([],[]) gated_insts of {
484             (_, []) -> (insts, []) ;    -- None picked
485             (gated_insts', iface_insts') -> 
486
487           (extendNameEnv insts cls gated_insts', iface_insts') }}
488
489         -- Reverses the gated decls, but that doesn't matter
490     choose (gis, decls) (gates, decl)
491         | any (`elem` tycons) gates = (gis,                decl:decls)
492         | otherwise                 = ((gates,decl) : gis, decls)
493 \end{code}
494
495 %************************************************************************
496 %*                                                                      *
497                 Rules
498 %*                                                                      *
499 %************************************************************************
500
501 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
502 are in the type environment.  However, remember that typechecking a Rule may 
503 (as a side effect) augment the type envt, and so we may need to iterate the process.
504
505 \begin{code}
506 selectRules :: RulePool 
507             -> [Name]           -- Names of things being added
508             -> TypeEnv          -- New type env, including things being added
509             -> (RulePool, [(ModuleName, IfaceRule)])
510 selectRules (Pool rules n_in n_out) new_names type_env
511   = (Pool rules' n_in (n_out + length iface_rules), iface_rules)
512   where
513     (rules', iface_rules) = foldl select_one (rules, []) new_names
514
515     select_one :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Name
516                -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
517     select_one (rules, decls) name
518         = case lookupNameEnv rules name of
519             Nothing          -> (rules, decls)
520             Just gated_rules -> foldl filter_rule (delFromNameEnv rules name, decls) gated_rules
521
522     filter_rule :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Gated IfaceRule 
523                 -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
524     filter_rule (rules, decls) (rule_fvs, rule)
525         = case [fv | fv <- rule_fvs, not (fv `elemNameEnv` type_env)] of
526             [] ->       -- No remaining FVs, so slurp it
527                         (rules, rule:decls)
528             fvs ->      -- There leftover fvs, so toss it back in the pool
529                         (addRuleToPool rules rule fvs, decls)
530
531 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
532 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
533                         ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
534   = bindIfaceBndrs bndrs        $ \ bndrs' ->
535     do  { fn <- tcIfaceExtId fn_rdr
536         ; args' <- mappM tcIfaceExpr args
537         ; rhs'  <- tcIfaceExpr rhs
538         ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
539
540 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
541   = do  { fn <- tcIfaceExtId fn_rdr
542         ; returnM (fn, core_rule) }
543 \end{code}
544
545
546 %************************************************************************
547 %*                                                                      *
548                         Types
549 %*                                                                      *
550 %************************************************************************
551
552 \begin{code}
553 tcIfaceKind :: IfaceKind -> Kind
554 tcIfaceKind IfaceOpenTypeKind     = openTypeKind
555 tcIfaceKind IfaceLiftedTypeKind   = liftedTypeKind
556 tcIfaceKind IfaceUnliftedTypeKind = unliftedTypeKind
557 tcIfaceKind (IfaceFunKind k1 k2)  = mkArrowKind (tcIfaceKind k1) (tcIfaceKind k2)
558
559 -----------------------------------------
560 tcIfaceType :: IfaceType -> IfL Type
561 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
562 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
563 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
564 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
565 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
566 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
567
568 tcIfaceTypes tys = mapM tcIfaceType tys
569
570 -----------------------------------------
571 tcIfacePredType :: IfacePredType -> IfL PredType
572 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
573 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
574
575 -----------------------------------------
576 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
577 tcIfaceCtxt sts = mappM tcIfacePredType sts
578 \end{code}
579
580
581 %************************************************************************
582 %*                                                                      *
583                         Core
584 %*                                                                      *
585 %************************************************************************
586
587 \begin{code}
588 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
589 tcIfaceExpr (IfaceType ty)
590   = tcIfaceType ty              `thenM` \ ty' ->
591     returnM (Type ty')
592
593 tcIfaceExpr (IfaceLcl name)
594   = tcIfaceLclId name   `thenM` \ id ->
595     returnM (Var id)
596
597 tcIfaceExpr (IfaceExt gbl)
598   = tcIfaceExtId gbl    `thenM` \ id ->
599     returnM (Var id)
600
601 tcIfaceExpr (IfaceLit lit)
602   = returnM (Lit lit)
603
604 tcIfaceExpr (IfaceFCall cc ty)
605   = tcIfaceType ty      `thenM` \ ty' ->
606     newUnique           `thenM` \ u ->
607     returnM (Var (mkFCallId u cc ty'))
608
609 tcIfaceExpr (IfaceTuple boxity args) 
610   = mappM tcIfaceExpr args      `thenM` \ args' ->
611     let
612         -- Put the missing type arguments back in
613         con_args = map (Type . exprType) args' ++ args'
614     in
615     returnM (mkApps (Var con_id) con_args)
616   where
617     arity = length args
618     con_id = dataConWorkId (tupleCon boxity arity)
619     
620
621 tcIfaceExpr (IfaceLam bndr body)
622   = bindIfaceBndr bndr          $ \ bndr' ->
623     tcIfaceExpr body            `thenM` \ body' ->
624     returnM (Lam bndr' body')
625
626 tcIfaceExpr (IfaceApp fun arg)
627   = tcIfaceExpr fun             `thenM` \ fun' ->
628     tcIfaceExpr arg             `thenM` \ arg' ->
629     returnM (App fun' arg')
630
631 tcIfaceExpr (IfaceCase scrut case_bndr alts) 
632   = tcIfaceExpr scrut           `thenM` \ scrut' ->
633     newIfaceName case_bndr      `thenM` \ case_bndr_name ->
634     let
635         scrut_ty   = exprType scrut'
636         case_bndr' = mkLocalId case_bndr_name scrut_ty
637         tc_app     = splitTyConApp scrut_ty
638                 -- NB: Won't always succeed (polymoprhic case)
639                 --     but won't be demanded in those cases
640                 -- NB: not tcSplitTyConApp; we are looking at Core here
641                 --     look through non-rec newtypes to find the tycon that
642                 --     corresponds to the datacon in this case alternative
643     in
644     extendIfaceIdEnv [case_bndr']       $
645     mappM (tcIfaceAlt tc_app) alts      `thenM` \ alts' ->
646     returnM (Case scrut' case_bndr' alts')
647
648 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
649   = tcIfaceExpr rhs             `thenM` \ rhs' ->
650     bindIfaceId bndr            $ \ bndr' ->
651     tcIfaceExpr body            `thenM` \ body' ->
652     returnM (Let (NonRec bndr' rhs') body')
653
654 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
655   = bindIfaceIds bndrs          $ \ bndrs' ->
656     mappM tcIfaceExpr rhss      `thenM` \ rhss' ->
657     tcIfaceExpr body            `thenM` \ body' ->
658     returnM (Let (Rec (bndrs' `zip` rhss')) body')
659   where
660     (bndrs, rhss) = unzip pairs
661
662 tcIfaceExpr (IfaceNote note expr) 
663   = tcIfaceExpr expr            `thenM` \ expr' ->
664     case note of
665         IfaceCoerce to_ty -> tcIfaceType to_ty  `thenM` \ to_ty' ->
666                              returnM (Note (Coerce to_ty'
667                                                    (exprType expr')) expr')
668         IfaceInlineCall   -> returnM (Note InlineCall expr')
669         IfaceInlineMe     -> returnM (Note InlineMe   expr')
670         IfaceSCC cc       -> returnM (Note (SCC cc)   expr')
671         IfaceCoreNote n   -> returnM (Note (CoreNote n) expr')
672
673 -------------------------
674 tcIfaceAlt _ (IfaceDefault, names, rhs)
675   = ASSERT( null names )
676     tcIfaceExpr rhs             `thenM` \ rhs' ->
677     returnM (DEFAULT, [], rhs')
678   
679 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
680   = ASSERT( null names )
681     tcIfaceExpr rhs             `thenM` \ rhs' ->
682     returnM (LitAlt lit, [], rhs')
683
684 -- A case alternative is made quite a bit more complicated
685 -- by the fact that we omit type annotations because we can
686 -- work them out.  True enough, but its not that easy!
687 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
688   = let 
689         tycon_mod = nameModuleName (tyConName tycon)
690     in
691     tcIfaceDataCon (ExtPkg tycon_mod data_occ)  `thenM` \ con ->
692     newIfaceNames arg_occs                      `thenM` \ arg_names ->
693     let
694         ex_tyvars   = dataConExistentialTyVars con
695         main_tyvars = tyConTyVars tycon
696         ex_tyvars'  = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars] 
697         ex_tys'     = mkTyVarTys ex_tyvars'
698         arg_tys     = dataConArgTys con (inst_tys ++ ex_tys')
699         id_names    = dropList ex_tyvars arg_names
700         arg_ids
701 #ifdef DEBUG
702                 | not (equalLength id_names arg_tys)
703                 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
704                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
705                                          ppr arg_tys)
706                 | otherwise
707 #endif
708                 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
709     in
710     ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
711              ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$  ppr main_tyvars  )
712     extendIfaceTyVarEnv ex_tyvars'      $
713     extendIfaceIdEnv arg_ids            $
714     tcIfaceExpr rhs                     `thenM` \ rhs' ->
715     returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
716
717 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
718   = newIfaceNames arg_occs      `thenM` \ arg_names ->
719     let
720         [con]   = tyConDataCons tycon
721         arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
722     in
723     ASSERT( isTupleTyCon tycon )
724     extendIfaceIdEnv arg_ids            $
725     tcIfaceExpr rhs                     `thenM` \ rhs' ->
726     returnM (DataAlt con, arg_ids, rhs')
727 \end{code}
728
729
730 \begin{code}
731 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
732 tcExtCoreBindings mod []     = return []
733 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
734
735 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
736 do_one mod (IfaceNonRec bndr rhs) thing_inside
737   = do  { rhs' <- tcIfaceExpr rhs
738         ; bndr' <- newExtCoreBndr mod bndr
739         ; extendIfaceIdEnv [bndr'] $ do 
740         { core_binds <- thing_inside
741         ; return (NonRec bndr' rhs' : core_binds) }}
742
743 do_one mod (IfaceRec pairs) thing_inside
744   = do  { bndrs' <- mappM (newExtCoreBndr mod) bndrs
745         ; extendIfaceIdEnv bndrs' $ do
746         { rhss' <- mappM tcIfaceExpr rhss
747         ; core_binds <- thing_inside
748         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
749   where
750     (bndrs,rhss) = unzip pairs
751 \end{code}
752
753
754 %************************************************************************
755 %*                                                                      *
756                 IdInfo
757 %*                                                                      *
758 %************************************************************************
759
760 \begin{code}
761 tcIdInfo name ty NoInfo        = return vanillaIdInfo
762 tcIdInfo name ty DiscardedInfo = return vanillaIdInfo
763 tcIdInfo name ty (HasInfo iface_info)
764   = foldlM tcPrag init_info iface_info
765   where
766     -- Set the CgInfo to something sensible but uninformative before
767     -- we start; default assumption is that it has CAFs
768     init_info = vanillaIdInfo
769
770     tcPrag info HsNoCafRefs         = returnM (info `setCafInfo`   NoCafRefs)
771     tcPrag info (HsArity arity)     = returnM (info `setArityInfo` arity)
772     tcPrag info (HsStrictness str)  = returnM (info `setAllStrictnessInfo` Just str)
773
774         -- The next two are lazy, so they don't transitively suck stuff in
775     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
776     tcPrag info (HsUnfold inline_prag expr)
777         = tcPragExpr name expr  `thenM` \ maybe_expr' ->
778           let
779                 -- maybe_expr' doesn't get looked at if the unfolding
780                 -- is never inspected; so the typecheck doesn't even happen
781                 unfold_info = case maybe_expr' of
782                                 Nothing    -> noUnfolding
783                                 Just expr' -> mkTopUnfolding expr' 
784           in
785           returnM (info `setUnfoldingInfoLazily` unfold_info
786                         `setInlinePragInfo`      inline_prag)
787 \end{code}
788
789 \begin{code}
790 tcWorkerInfo ty info wkr_name arity
791   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
792
793         -- We return without testing maybe_wkr_id, but as soon as info is
794         -- looked at we will test it.  That's ok, because its outside the
795         -- knot; and there seems no big reason to further defer the
796         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
797         -- over the unfolding until it's actually used does seem worth while.)
798         ; us <- newUniqueSupply
799
800         ; returnM (case mb_wkr_id of
801                      Nothing     -> info
802                      Just wkr_id -> add_wkr_info us wkr_id info) }
803   where
804     doc = text "Worker for" <+> ppr wkr_name
805     add_wkr_info us wkr_id info
806         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
807                `setWorkerInfo`           HasWorker wkr_id arity
808
809     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
810
811         -- We are relying here on strictness info always appearing 
812         -- before worker info,  fingers crossed ....
813     strict_sig = case newStrictnessInfo info of
814                    Just sig -> sig
815                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
816 \end{code}
817
818 For unfoldings we try to do the job lazily, so that we never type check
819 an unfolding that isn't going to be looked at.
820
821 \begin{code}
822 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
823 tcPragExpr name expr
824   = forkM_maybe doc $
825     tcIfaceExpr expr            `thenM` \ core_expr' ->
826
827                 -- Check for type consistency in the unfolding
828     ifOptM Opt_DoCoreLinting (
829         get_in_scope_ids                        `thenM` \ in_scope -> 
830         case lintUnfolding noSrcLoc in_scope core_expr' of
831           Nothing       -> returnM ()
832           Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
833     )                           `thenM_`
834
835    returnM core_expr'   
836   where
837     doc = text "Unfolding of" <+> ppr name
838     get_in_scope_ids    -- Urgh; but just for linting
839         = setLclEnv () $ 
840           do    { env <- getGblEnv 
841                 ; case if_rec_types env of {
842                           Nothing -> return [] ;
843                           Just (_, get_env) -> do
844                 { type_env <- get_env
845                 ; return (typeEnvIds type_env) }}}
846 \end{code}
847
848
849
850 %************************************************************************
851 %*                                                                      *
852                 Bindings
853 %*                                                                      *
854 %************************************************************************
855
856 \begin{code}
857 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
858 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
859   = bindIfaceId bndr thing_inside
860 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
861   = bindIfaceTyVar bndr thing_inside
862     
863 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
864 bindIfaceBndrs []     thing_inside = thing_inside []
865 bindIfaceBndrs (b:bs) thing_inside
866   = bindIfaceBndr b     $ \ b' ->
867     bindIfaceBndrs bs   $ \ bs' ->
868     thing_inside (b':bs')
869
870 -----------------------
871 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
872 bindIfaceId (occ, ty) thing_inside
873   = do  { name <- newIfaceName occ
874         ; ty' <- tcIfaceType ty
875         ; let { id = mkLocalId name ty' }
876         ; extendIfaceIdEnv [id] (thing_inside id) }
877     
878 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
879 bindIfaceIds bndrs thing_inside
880   = do  { names <- newIfaceNames occs
881         ; tys' <- mappM tcIfaceType tys
882         ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
883         ; extendIfaceIdEnv ids (thing_inside ids) }
884   where
885     (occs,tys) = unzip bndrs
886
887
888 -----------------------
889 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
890 newExtCoreBndr mod (occ, ty)
891   = do  { name <- newGlobalBinder mod occ Nothing noSrcLoc
892         ; ty' <- tcIfaceType ty
893         ; return (mkLocalId name ty') }
894
895 -----------------------
896 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
897 bindIfaceTyVar (occ,kind) thing_inside
898   = do  { name <- newIfaceName occ
899         ; let tyvar = mk_iface_tyvar name kind
900         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
901
902 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
903 bindIfaceTyVars bndrs thing_inside
904   = do  { names <- newIfaceNames occs
905         ; let tyvars = zipWith mk_iface_tyvar names kinds
906         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
907   where
908     (occs,kinds) = unzip bndrs
909
910 mk_iface_tyvar name kind = mkTyVar name (tcIfaceKind kind)
911 \end{code}