[project @ 2003-10-09 15:38:22 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
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         -- Empty => finish up rapidly, without writing to eps
449         ; if null iface_insts then
450                 return (eps_inst_env eps)
451           else do
452         { writeMutVar eps_var (eps {eps_insts = inst_pool'})
453
454         -- Typecheck the new instances
455         ; dfuns <- initIfaceTcRn (mappM tc_inst iface_insts)
456
457         -- And put them in the package instance environment
458         ; updateEps ( \ eps ->
459             let 
460                 inst_env' = foldl extendInstEnv (eps_inst_env eps) dfuns
461             in
462             (eps { eps_inst_env = inst_env' }, inst_env')
463         )}}
464   where
465     wired_doc = ptext SLIT("Need home inteface for wired-in thing")
466
467 tc_inst (mod, inst) = initIfaceLcl mod (tcIfaceInst inst)
468
469 tcIfaceInst :: IfaceInst -> IfL DFunId
470 tcIfaceInst (IfaceInst { ifDFun = dfun_occ })
471   = tcIfaceExtId (LocalTop dfun_occ)
472
473 selectInsts :: InstPool -> Name -> [Name] -> (InstPool, [(ModuleName, IfaceInst)])
474 selectInsts pool@(Pool insts n_in n_out) cls tycons
475   = (Pool insts' n_in (n_out + length iface_insts), iface_insts)
476   where
477     (insts', iface_insts) 
478         = case lookupNameEnv insts cls of {
479                 Nothing -> (insts, []) ;
480                 Just gated_insts -> 
481         
482           case foldl choose ([],[]) gated_insts of {
483             (_, []) -> (insts, []) ;    -- None picked
484             (gated_insts', iface_insts') -> 
485
486           (extendNameEnv insts cls gated_insts', iface_insts') }}
487
488         -- Reverses the gated decls, but that doesn't matter
489     choose (gis, decls) (gates, decl)
490         | any (`elem` tycons) gates = (gis,                decl:decls)
491         | otherwise                 = ((gates,decl) : gis, decls)
492 \end{code}
493
494 %************************************************************************
495 %*                                                                      *
496                 Rules
497 %*                                                                      *
498 %************************************************************************
499
500 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
501 are in the type environment.  However, remember that typechecking a Rule may 
502 (as a side effect) augment the type envt, and so we may need to iterate the process.
503
504 \begin{code}
505 selectRules :: RulePool 
506             -> [Name]           -- Names of things being added
507             -> TypeEnv          -- New type env, including things being added
508             -> (RulePool, [(ModuleName, IfaceRule)])
509 selectRules (Pool rules n_in n_out) new_names type_env
510   = (Pool rules' n_in (n_out + length iface_rules), iface_rules)
511   where
512     (rules', iface_rules) = foldl select_one (rules, []) new_names
513
514     select_one :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Name
515                -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
516     select_one (rules, decls) name
517         = case lookupNameEnv rules name of
518             Nothing          -> (rules, decls)
519             Just gated_rules -> foldl filter_rule (delFromNameEnv rules name, decls) gated_rules
520
521     filter_rule :: (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)]) -> Gated IfaceRule 
522                 -> (NameEnv [Gated IfaceRule], [(ModuleName, IfaceRule)])
523     filter_rule (rules, decls) (rule_fvs, rule)
524         = case [fv | fv <- rule_fvs, not (fv `elemNameEnv` type_env)] of
525             [] ->       -- No remaining FVs, so slurp it
526                         (rules, rule:decls)
527             fvs ->      -- There leftover fvs, so toss it back in the pool
528                         (addRuleToPool rules rule fvs, decls)
529
530 tcIfaceRule :: IfaceRule -> IfL IdCoreRule
531 tcIfaceRule (IfaceRule {ifRuleName = rule_name, ifActivation = act, ifRuleBndrs = bndrs,
532                         ifRuleHead = fn_rdr, ifRuleArgs = args, ifRuleRhs = rhs })
533   = bindIfaceBndrs bndrs        $ \ bndrs' ->
534     do  { fn <- tcIfaceExtId fn_rdr
535         ; args' <- mappM tcIfaceExpr args
536         ; rhs'  <- tcIfaceExpr rhs
537         ; returnM (fn, (Rule rule_name act bndrs' args' rhs')) }
538
539 tcIfaceRule (IfaceBuiltinRule fn_rdr core_rule)
540   = do  { fn <- tcIfaceExtId fn_rdr
541         ; returnM (fn, core_rule) }
542 \end{code}
543
544
545 %************************************************************************
546 %*                                                                      *
547                         Types
548 %*                                                                      *
549 %************************************************************************
550
551 \begin{code}
552 tcIfaceKind :: IfaceKind -> Kind
553 tcIfaceKind IfaceOpenTypeKind     = openTypeKind
554 tcIfaceKind IfaceLiftedTypeKind   = liftedTypeKind
555 tcIfaceKind IfaceUnliftedTypeKind = unliftedTypeKind
556 tcIfaceKind (IfaceFunKind k1 k2)  = mkArrowKind (tcIfaceKind k1) (tcIfaceKind k2)
557
558 -----------------------------------------
559 tcIfaceType :: IfaceType -> IfL Type
560 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
561 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
562 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
563 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkGenTyConApp tc' ts') }
564 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
565 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
566
567 tcIfaceTypes tys = mapM tcIfaceType tys
568
569 -----------------------------------------
570 tcIfacePredType :: IfacePredType -> IfL PredType
571 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
572 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
573
574 -----------------------------------------
575 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
576 tcIfaceCtxt sts = mappM tcIfacePredType sts
577 \end{code}
578
579
580 %************************************************************************
581 %*                                                                      *
582                         Core
583 %*                                                                      *
584 %************************************************************************
585
586 \begin{code}
587 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
588 tcIfaceExpr (IfaceType ty)
589   = tcIfaceType ty              `thenM` \ ty' ->
590     returnM (Type ty')
591
592 tcIfaceExpr (IfaceLcl name)
593   = tcIfaceLclId name   `thenM` \ id ->
594     returnM (Var id)
595
596 tcIfaceExpr (IfaceExt gbl)
597   = tcIfaceExtId gbl    `thenM` \ id ->
598     returnM (Var id)
599
600 tcIfaceExpr (IfaceLit lit)
601   = returnM (Lit lit)
602
603 tcIfaceExpr (IfaceFCall cc ty)
604   = tcIfaceType ty      `thenM` \ ty' ->
605     newUnique           `thenM` \ u ->
606     returnM (Var (mkFCallId u cc ty'))
607
608 tcIfaceExpr (IfaceTuple boxity args) 
609   = mappM tcIfaceExpr args      `thenM` \ args' ->
610     let
611         -- Put the missing type arguments back in
612         con_args = map (Type . exprType) args' ++ args'
613     in
614     returnM (mkApps (Var con_id) con_args)
615   where
616     arity = length args
617     con_id = dataConWorkId (tupleCon boxity arity)
618     
619
620 tcIfaceExpr (IfaceLam bndr body)
621   = bindIfaceBndr bndr          $ \ bndr' ->
622     tcIfaceExpr body            `thenM` \ body' ->
623     returnM (Lam bndr' body')
624
625 tcIfaceExpr (IfaceApp fun arg)
626   = tcIfaceExpr fun             `thenM` \ fun' ->
627     tcIfaceExpr arg             `thenM` \ arg' ->
628     returnM (App fun' arg')
629
630 tcIfaceExpr (IfaceCase scrut case_bndr alts) 
631   = tcIfaceExpr scrut           `thenM` \ scrut' ->
632     newIfaceName case_bndr      `thenM` \ case_bndr_name ->
633     let
634         scrut_ty   = exprType scrut'
635         case_bndr' = mkLocalId case_bndr_name scrut_ty
636         tc_app     = splitTyConApp scrut_ty
637                 -- NB: Won't always succeed (polymoprhic case)
638                 --     but won't be demanded in those cases
639                 -- NB: not tcSplitTyConApp; we are looking at Core here
640                 --     look through non-rec newtypes to find the tycon that
641                 --     corresponds to the datacon in this case alternative
642     in
643     extendIfaceIdEnv [case_bndr']       $
644     mappM (tcIfaceAlt tc_app) alts      `thenM` \ alts' ->
645     returnM (Case scrut' case_bndr' alts')
646
647 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
648   = tcIfaceExpr rhs             `thenM` \ rhs' ->
649     bindIfaceId bndr            $ \ bndr' ->
650     tcIfaceExpr body            `thenM` \ body' ->
651     returnM (Let (NonRec bndr' rhs') body')
652
653 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
654   = bindIfaceIds bndrs          $ \ bndrs' ->
655     mappM tcIfaceExpr rhss      `thenM` \ rhss' ->
656     tcIfaceExpr body            `thenM` \ body' ->
657     returnM (Let (Rec (bndrs' `zip` rhss')) body')
658   where
659     (bndrs, rhss) = unzip pairs
660
661 tcIfaceExpr (IfaceNote note expr) 
662   = tcIfaceExpr expr            `thenM` \ expr' ->
663     case note of
664         IfaceCoerce to_ty -> tcIfaceType to_ty  `thenM` \ to_ty' ->
665                              returnM (Note (Coerce to_ty'
666                                                    (exprType expr')) expr')
667         IfaceInlineCall   -> returnM (Note InlineCall expr')
668         IfaceInlineMe     -> returnM (Note InlineMe   expr')
669         IfaceSCC cc       -> returnM (Note (SCC cc)   expr')
670         IfaceCoreNote n   -> returnM (Note (CoreNote n) expr')
671
672 -------------------------
673 tcIfaceAlt _ (IfaceDefault, names, rhs)
674   = ASSERT( null names )
675     tcIfaceExpr rhs             `thenM` \ rhs' ->
676     returnM (DEFAULT, [], rhs')
677   
678 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
679   = ASSERT( null names )
680     tcIfaceExpr rhs             `thenM` \ rhs' ->
681     returnM (LitAlt lit, [], rhs')
682
683 -- A case alternative is made quite a bit more complicated
684 -- by the fact that we omit type annotations because we can
685 -- work them out.  True enough, but its not that easy!
686 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
687   = let 
688         tycon_mod = nameModuleName (tyConName tycon)
689     in
690     tcIfaceDataCon (ExtPkg tycon_mod data_occ)  `thenM` \ con ->
691     newIfaceNames arg_occs                      `thenM` \ arg_names ->
692     let
693         ex_tyvars   = dataConExistentialTyVars con
694         main_tyvars = tyConTyVars tycon
695         ex_tyvars'  = [mkTyVar name (tyVarKind tv) | (name,tv) <- arg_names `zip` ex_tyvars] 
696         ex_tys'     = mkTyVarTys ex_tyvars'
697         arg_tys     = dataConArgTys con (inst_tys ++ ex_tys')
698         id_names    = dropList ex_tyvars arg_names
699         arg_ids
700 #ifdef DEBUG
701                 | not (equalLength id_names arg_tys)
702                 = pprPanic "tcIfaceAlts" (ppr (con, arg_names, rhs) $$
703                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
704                                          ppr arg_tys)
705                 | otherwise
706 #endif
707                 = zipWithEqual "tcIfaceAlts" mkLocalId id_names arg_tys
708     in
709     ASSERT2( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars,
710              ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) $$ ppr arg_tys $$  ppr main_tyvars  )
711     extendIfaceTyVarEnv ex_tyvars'      $
712     extendIfaceIdEnv arg_ids            $
713     tcIfaceExpr rhs                     `thenM` \ rhs' ->
714     returnM (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
715
716 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
717   = newIfaceNames arg_occs      `thenM` \ arg_names ->
718     let
719         [con]   = tyConDataCons tycon
720         arg_ids = zipWithEqual "tcIfaceAlts" mkLocalId arg_names inst_tys
721     in
722     ASSERT( isTupleTyCon tycon )
723     extendIfaceIdEnv arg_ids            $
724     tcIfaceExpr rhs                     `thenM` \ rhs' ->
725     returnM (DataAlt con, arg_ids, rhs')
726 \end{code}
727
728
729 \begin{code}
730 tcExtCoreBindings :: Module -> [IfaceBinding] -> IfL [CoreBind] -- Used for external core
731 tcExtCoreBindings mod []     = return []
732 tcExtCoreBindings mod (b:bs) = do_one mod b (tcExtCoreBindings mod bs)
733
734 do_one :: Module -> IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
735 do_one mod (IfaceNonRec bndr rhs) thing_inside
736   = do  { rhs' <- tcIfaceExpr rhs
737         ; bndr' <- newExtCoreBndr mod bndr
738         ; extendIfaceIdEnv [bndr'] $ do 
739         { core_binds <- thing_inside
740         ; return (NonRec bndr' rhs' : core_binds) }}
741
742 do_one mod (IfaceRec pairs) thing_inside
743   = do  { bndrs' <- mappM (newExtCoreBndr mod) bndrs
744         ; extendIfaceIdEnv bndrs' $ do
745         { rhss' <- mappM tcIfaceExpr rhss
746         ; core_binds <- thing_inside
747         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
748   where
749     (bndrs,rhss) = unzip pairs
750 \end{code}
751
752
753 %************************************************************************
754 %*                                                                      *
755                 IdInfo
756 %*                                                                      *
757 %************************************************************************
758
759 \begin{code}
760 tcIdInfo name ty NoInfo        = return vanillaIdInfo
761 tcIdInfo name ty DiscardedInfo = return vanillaIdInfo
762 tcIdInfo name ty (HasInfo iface_info)
763   = foldlM tcPrag init_info iface_info
764   where
765     -- Set the CgInfo to something sensible but uninformative before
766     -- we start; default assumption is that it has CAFs
767     init_info = vanillaIdInfo
768
769     tcPrag info HsNoCafRefs         = returnM (info `setCafInfo`   NoCafRefs)
770     tcPrag info (HsArity arity)     = returnM (info `setArityInfo` arity)
771     tcPrag info (HsStrictness str)  = returnM (info `setAllStrictnessInfo` Just str)
772
773         -- The next two are lazy, so they don't transitively suck stuff in
774     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
775     tcPrag info (HsUnfold inline_prag expr)
776         = tcPragExpr name expr  `thenM` \ maybe_expr' ->
777           let
778                 -- maybe_expr' doesn't get looked at if the unfolding
779                 -- is never inspected; so the typecheck doesn't even happen
780                 unfold_info = case maybe_expr' of
781                                 Nothing    -> noUnfolding
782                                 Just expr' -> mkTopUnfolding expr' 
783           in
784           returnM (info `setUnfoldingInfoLazily` unfold_info
785                         `setInlinePragInfo`      inline_prag)
786 \end{code}
787
788 \begin{code}
789 tcWorkerInfo ty info wkr_name arity
790   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId (LocalTop wkr_name))
791
792         -- We return without testing maybe_wkr_id, but as soon as info is
793         -- looked at we will test it.  That's ok, because its outside the
794         -- knot; and there seems no big reason to further defer the
795         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
796         -- over the unfolding until it's actually used does seem worth while.)
797         ; us <- newUniqueSupply
798
799         ; returnM (case mb_wkr_id of
800                      Nothing     -> info
801                      Just wkr_id -> add_wkr_info us wkr_id info) }
802   where
803     doc = text "Worker for" <+> ppr wkr_name
804     add_wkr_info us wkr_id info
805         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
806                `setWorkerInfo`           HasWorker wkr_id arity
807
808     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
809
810         -- We are relying here on strictness info always appearing 
811         -- before worker info,  fingers crossed ....
812     strict_sig = case newStrictnessInfo info of
813                    Just sig -> sig
814                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr_name)
815 \end{code}
816
817 For unfoldings we try to do the job lazily, so that we never type check
818 an unfolding that isn't going to be looked at.
819
820 \begin{code}
821 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
822 tcPragExpr name expr
823   = forkM_maybe doc $
824     tcIfaceExpr expr            `thenM` \ core_expr' ->
825
826                 -- Check for type consistency in the unfolding
827     ifOptM Opt_DoCoreLinting (
828         get_in_scope_ids                        `thenM` \ in_scope -> 
829         case lintUnfolding noSrcLoc in_scope core_expr' of
830           Nothing       -> returnM ()
831           Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
832     )                           `thenM_`
833
834    returnM core_expr'   
835   where
836     doc = text "Unfolding of" <+> ppr name
837     get_in_scope_ids    -- Urgh; but just for linting
838         = setLclEnv () $ 
839           do    { env <- getGblEnv 
840                 ; case if_rec_types env of {
841                           Nothing -> return [] ;
842                           Just (_, get_env) -> do
843                 { type_env <- get_env
844                 ; return (typeEnvIds type_env) }}}
845 \end{code}
846
847
848
849 %************************************************************************
850 %*                                                                      *
851                 Bindings
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
857 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
858   = bindIfaceId bndr thing_inside
859 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
860   = bindIfaceTyVar bndr thing_inside
861     
862 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
863 bindIfaceBndrs []     thing_inside = thing_inside []
864 bindIfaceBndrs (b:bs) thing_inside
865   = bindIfaceBndr b     $ \ b' ->
866     bindIfaceBndrs bs   $ \ bs' ->
867     thing_inside (b':bs')
868
869 -----------------------
870 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
871 bindIfaceId (occ, ty) thing_inside
872   = do  { name <- newIfaceName occ
873         ; ty' <- tcIfaceType ty
874         ; let { id = mkLocalId name ty' }
875         ; extendIfaceIdEnv [id] (thing_inside id) }
876     
877 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
878 bindIfaceIds bndrs thing_inside
879   = do  { names <- newIfaceNames occs
880         ; tys' <- mappM tcIfaceType tys
881         ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
882         ; extendIfaceIdEnv ids (thing_inside ids) }
883   where
884     (occs,tys) = unzip bndrs
885
886
887 -----------------------
888 newExtCoreBndr :: Module -> (OccName, IfaceType) -> IfL Id
889 newExtCoreBndr mod (occ, ty)
890   = do  { name <- newGlobalBinder mod occ Nothing noSrcLoc
891         ; ty' <- tcIfaceType ty
892         ; return (mkLocalId name ty') }
893
894 -----------------------
895 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
896 bindIfaceTyVar (occ,kind) thing_inside
897   = do  { name <- newIfaceName occ
898         ; let tyvar = mk_iface_tyvar name kind
899         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
900
901 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
902 bindIfaceTyVars bndrs thing_inside
903   = do  { names <- newIfaceNames occs
904         ; let tyvars = zipWith mk_iface_tyvar names kinds
905         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
906   where
907     (occs,kinds) = unzip bndrs
908
909 mk_iface_tyvar name kind = mkTyVar name (tcIfaceKind kind)
910 \end{code}