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