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