[project @ 2005-05-04 15:46:39 by simonmar]
[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, checkWiredInTyCon, tcHiBootIface, typecheckIface, 
9         tcIfaceDecl, tcIfaceInst, tcIfaceRule, tcIfaceGlobal, 
10         tcExtCoreBindings
11  ) where
12
13 #include "HsVersions.h"
14
15 import IfaceSyn
16 import LoadIface        ( loadInterface, loadWiredInHomeIface,
17                           loadDecls, findAndReadIface )
18 import IfaceEnv         ( lookupIfaceTop, lookupIfaceExt, newGlobalBinder, 
19                           extendIfaceIdEnv, extendIfaceTyVarEnv, newIPName,
20                           tcIfaceTyVar, tcIfaceLclId, lookupIfaceTc, 
21                           newIfaceName, newIfaceNames, ifaceExportNames )
22 import BuildTyCl        ( buildSynTyCon, buildAlgTyCon, buildDataCon, buildClass,
23                           mkAbstractTyConRhs, mkDataTyConRhs, mkNewTyConRhs )
24 import TcRnMonad
25 import TcType           ( hoistForAllTys )      -- TEMPORARY HACK
26 import Type             ( liftedTypeKind, splitTyConApp, mkSynTy, mkTyConApp,
27                           mkTyVarTys, ThetaType, 
28                           mkGenTyConApp )       -- Don't remove this... see mkIfTcApp
29 import TypeRep          ( Type(..), PredType(..) )
30 import TyCon            ( TyCon, tyConName, isSynTyCon )
31 import HscTypes         ( ExternalPackageState(..), 
32                           TyThing(..), tyThingClass, tyThingTyCon, 
33                           ModIface(..), ModDetails(..), HomeModInfo(..),
34                           emptyModDetails, lookupTypeEnv, lookupType, typeEnvIds )
35 import InstEnv          ( Instance(..), mkImportedInstance )
36 import CoreSyn
37 import CoreUtils        ( exprType )
38 import CoreUnfold
39 import CoreLint         ( lintUnfolding )
40 import WorkWrap         ( mkWrapper )
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            ( tyConDataCons, isTupleTyCon, mkForeignTyCon )
49 import DataCon          ( DataCon, dataConWorkId, dataConTyVars, dataConArgTys, isVanillaDataCon )
50 import TysWiredIn       ( tupleCon, tupleTyCon, listTyCon, intTyCon, boolTyCon, charTyCon, parrTyCon )
51 import Var              ( TyVar, mkTyVar, tyVarKind )
52 import Name             ( Name, nameModule, nameIsLocalOrFrom, isWiredInName,
53                           wiredInNameTyThing_maybe, nameParent )
54 import NameEnv
55 import OccName          ( OccName )
56 import Module           ( Module, lookupModuleEnv )
57 import UniqSupply       ( initUs_ )
58 import Outputable       
59 import ErrUtils         ( Message )
60 import Maybes           ( MaybeErr(..) )
61 import SrcLoc           ( noSrcLoc )
62 import Util             ( zipWithEqual, dropList, equalLength )
63 import DynFlags         ( DynFlag(..), isOneShot )
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 -> TcM TyThing
111 -- Entry point for *source-code* uses of importDecl
112 tcImportDecl name 
113   | Just thing <- wiredInNameTyThing_maybe name
114   = do  { initIfaceTcRn (loadWiredInHomeIface name) 
115         ; return thing }
116   | otherwise
117   = do  { traceIf (text "tcLookupGlobal" <+> ppr name)
118         ; mb_thing <- initIfaceTcRn (importDecl name)
119         ; case mb_thing of
120             Succeeded thing -> return thing
121             Failed err      -> failWithTc err }
122
123 checkWiredInTyCon :: TyCon -> TcM ()
124 -- Ensure that the home module of the TyCon (and hence its instances)
125 -- are loaded. It might not be a wired-in tycon (see the calls in TcUnify),
126 -- in which case this is a no-op.
127 checkWiredInTyCon tc    
128   | not (isWiredInName tc_name) 
129   = return ()
130   | otherwise
131   = do  { mod <- getModule
132         ; if nameIsLocalOrFrom mod tc_name then
133                 -- Don't look for (non-existent) Float.hi when
134                 -- compiling Float.lhs, which mentions Float of course
135                 return ()
136           else  -- A bit yukky to call initIfaceTcRn here
137                 initIfaceTcRn (loadWiredInHomeIface tc_name) 
138         }
139   where
140     tc_name = tyConName tc
141
142 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
143 -- Get the TyThing for this Name from an interface file
144 -- It's not a wired-in thing -- the caller caught that
145 importDecl name
146   = ASSERT( not (isWiredInName name) )
147     do  { traceIf nd_doc
148
149         -- Load the interface, which should populate the PTE
150         ; mb_iface <- loadInterface nd_doc (nameModule name) ImportBySystem
151         ; case mb_iface of {
152                 Failed err_msg  -> return (Failed err_msg) ;
153                 Succeeded iface -> do
154
155         -- Now look it up again; this time we should find it
156         { eps <- getEps 
157         ; case lookupTypeEnv (eps_PTE eps) name of
158             Just thing -> return (Succeeded thing)
159             Nothing    -> return (Failed not_found_msg)
160     }}}
161   where
162     nd_doc = ptext SLIT("Need decl for") <+> ppr name
163     not_found_msg = hang (ptext SLIT("Can't find interface-file declaration for") <+> ppr (nameParent name))
164                        2 (vcat [ptext SLIT("Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
165                                 ptext SLIT("Use -ddump-if-trace to get an idea of which file caused the error")])
166 \end{code}
167
168 %************************************************************************
169 %*                                                                      *
170                 Type-checking a complete interface
171 %*                                                                      *
172 %************************************************************************
173
174 Suppose we discover we don't need to recompile.  Then we must type
175 check the old interface file.  This is a bit different to the
176 incremental type checking we do as we suck in interface files.  Instead
177 we do things similarly as when we are typechecking source decls: we
178 bring into scope the type envt for the interface all at once, using a
179 knot.  Remember, the decls aren't necessarily in dependency order --
180 and even if they were, the type decls might be mutually recursive.
181
182 \begin{code}
183 typecheckIface :: ModIface      -- Get the decls from here
184                -> TcRnIf gbl lcl ModDetails
185 typecheckIface iface
186   = initIfaceTc iface $ \ tc_env_var -> do
187         -- The tc_env_var is freshly allocated, private to 
188         -- type-checking this particular interface
189         {       -- Get the right set of decls and rules.  If we are compiling without -O
190                 -- we discard pragmas before typechecking, so that we don't "see"
191                 -- information that we shouldn't.  From a versioning point of view
192                 -- It's not actually *wrong* to do so, but in fact GHCi is unable 
193                 -- to handle unboxed tuples, so it must not see unfoldings.
194           ignore_prags <- doptM Opt_IgnoreInterfacePragmas
195
196                 -- Load & typecheck the decls
197         ; decl_things <- loadDecls ignore_prags (mi_decls iface)
198
199         ; let type_env = mkNameEnv decl_things
200         ; writeMutVar tc_env_var type_env
201
202                 -- Now do those rules and instances
203         ; let { rules | ignore_prags = []
204                       | otherwise    = mi_rules iface
205               ; dfuns = mi_insts iface
206               } 
207         ; dfuns <- mapM tcIfaceInst dfuns
208         ; rules <- mapM tcIfaceRule rules
209
210                 -- Exports
211         ; exports <-  ifaceExportNames (mi_exports iface)
212
213                 -- Finished
214         ; return (ModDetails {  md_types = type_env, 
215                                 md_insts = dfuns,
216                                 md_rules = rules,
217                                 md_exports = exports }) 
218     }
219 \end{code}
220
221
222 %************************************************************************
223 %*                                                                      *
224                 Type and class declarations
225 %*                                                                      *
226 %************************************************************************
227
228 \begin{code}
229 tcHiBootIface :: Module -> TcRn ModDetails
230 -- Load the hi-boot iface for the module being compiled,
231 -- if it indeed exists in the transitive closure of imports
232 -- Return the ModDetails, empty if no hi-boot iface
233 tcHiBootIface mod
234   = do  { traceIf (text "loadHiBootInterface" <+> ppr mod)
235
236         ; mode <- getGhciMode
237         ; if not (isOneShot mode)
238                 -- In --make and interactive mode, if this module has an hs-boot file
239                 -- we'll have compiled it already, and it'll be in the HPT
240           then do { hpt <- getHpt
241                   ; case lookupModuleEnv hpt mod of
242                       Just info -> return (hm_details info)
243                       Nothing   -> return emptyModDetails }
244           else do
245
246         -- OK, so we're in one-shot mode.  
247         -- In that case, we're read all the direct imports by now, 
248         -- so eps_is_boot will record if any of our imports mention us by 
249         -- way of hi-boot file
250         { eps <- getEps
251         ; case lookupModuleEnv (eps_is_boot eps) mod of {
252             Nothing -> return emptyModDetails ; -- The typical case
253
254             Just (_, False) -> failWithTc moduleLoop ;
255                 -- Someone below us imported us!
256                 -- This is a loop with no hi-boot in the way
257                 
258             Just (mod, True) ->         -- There's a hi-boot interface below us
259                 
260     do  { read_result <- findAndReadIface 
261                                 True    -- Explicit import? 
262                                 need mod
263                                 True    -- Hi-boot file
264
265         ; case read_result of
266                 Failed err               -> failWithTc (elaborate err)
267                 Succeeded (iface, _path) -> typecheckIface iface
268     }}}}
269   where
270     need = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
271                  <+> ptext SLIT("to compare against the Real Thing")
272
273     moduleLoop = ptext SLIT("Circular imports: module") <+> quotes (ppr mod) 
274                      <+> ptext SLIT("depends on itself")
275
276     elaborate err = hang (ptext SLIT("Could not find hi-boot interface for") <+> 
277                           quotes (ppr mod) <> colon) 4 err
278 \end{code}
279
280
281 %************************************************************************
282 %*                                                                      *
283                 Type and class declarations
284 %*                                                                      *
285 %************************************************************************
286
287 When typechecking a data type decl, we *lazily* (via forkM) typecheck
288 the constructor argument types.  This is in the hope that we may never
289 poke on those argument types, and hence may never need to load the
290 interface files for types mentioned in the arg types.
291
292 E.g.    
293         data Foo.S = MkS Baz.T
294 Mabye we can get away without even loading the interface for Baz!
295
296 This is not just a performance thing.  Suppose we have
297         data Foo.S = MkS Baz.T
298         data Baz.T = MkT Foo.S
299 (in different interface files, of course).
300 Now, first we load and typecheck Foo.S, and add it to the type envt.  
301 If we do explore MkS's argument, we'll load and typecheck Baz.T.
302 If we explore MkT's argument we'll find Foo.S already in the envt.  
303
304 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
305 typecheck the type Baz.T.  So we'd fault in Baz.T... and then need Foo.S...
306 which isn't done yet.
307
308 All very cunning. However, there is a rather subtle gotcha which bit
309 me when developing this stuff.  When we typecheck the decl for S, we
310 extend the type envt with S, MkS, and all its implicit Ids.  Suppose
311 (a bug, but it happened) that the list of implicit Ids depended in
312 turn on the constructor arg types.  Then the following sequence of
313 events takes place:
314         * we build a thunk <t> for the constructor arg tys
315         * we build a thunk for the extended type environment (depends on <t>)
316         * we write the extended type envt into the global EPS mutvar
317         
318 Now we look something up in the type envt
319         * that pulls on <t>
320         * which reads the global type envt out of the global EPS mutvar
321         * but that depends in turn on <t>
322
323 It's subtle, because, it'd work fine if we typechecked the constructor args 
324 eagerly -- they don't need the extended type envt.  They just get the extended
325 type envt by accident, because they look at it later.
326
327 What this means is that the implicitTyThings MUST NOT DEPEND on any of
328 the forkM stuff.
329
330
331 \begin{code}
332 tcIfaceDecl :: IfaceDecl -> IfL TyThing
333
334 tcIfaceDecl (IfaceId {ifName = occ_name, ifType = iface_type, ifIdInfo = info})
335   = do  { name <- lookupIfaceTop occ_name
336         ; ty <- tcIfaceType iface_type
337         ; info <- tcIdInfo name ty info
338         ; return (AnId (mkVanillaGlobal name ty info)) }
339
340 tcIfaceDecl (IfaceData {ifName = occ_name, 
341                         ifTyVars = tv_bndrs, 
342                         ifCtxt = ctxt,
343                         ifCons = rdr_cons, 
344                         ifVrcs = arg_vrcs, ifRec = is_rec, 
345                         ifGeneric = want_generic })
346   = do  { tc_name <- lookupIfaceTop occ_name
347         ; bindIfaceTyVars tv_bndrs $ \ tyvars -> do
348
349         { tycon <- fixM ( \ tycon -> do
350             { stupid_theta <- tcIfaceCtxt ctxt
351             ; cons  <- tcIfaceDataCons tycon tyvars rdr_cons
352             ; buildAlgTyCon tc_name tyvars stupid_theta
353                             cons arg_vrcs is_rec want_generic
354             })
355         ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
356         ; return (ATyCon tycon)
357     }}
358
359 tcIfaceDecl (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs, 
360                        ifSynRhs = rdr_rhs_ty, ifVrcs = arg_vrcs})
361    = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
362      { tc_name <- lookupIfaceTop occ_name
363      ; rhs_ty <- tcIfaceType rdr_rhs_ty
364      ; return (ATyCon (buildSynTyCon tc_name tyvars rhs_ty arg_vrcs))
365      }
366
367 tcIfaceDecl (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, ifTyVars = tv_bndrs, 
368                          ifFDs = rdr_fds, ifSigs = rdr_sigs, 
369                          ifVrcs = tc_vrcs, ifRec = tc_isrec })
370   = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
371     { cls_name <- lookupIfaceTop occ_name
372     ; ctxt <- tcIfaceCtxt rdr_ctxt
373     ; sigs <- mappM tc_sig rdr_sigs
374     ; fds  <- mappM tc_fd rdr_fds
375     ; cls  <- buildClass cls_name tyvars ctxt fds sigs tc_isrec tc_vrcs
376     ; return (AClass cls) }
377   where
378    tc_sig (IfaceClassOp occ dm rdr_ty)
379      = do { op_name <- lookupIfaceTop occ
380           ; op_ty   <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
381                 -- Must be done lazily for just the same reason as the 
382                 -- context of a data decl: the type sig might mention the
383                 -- class being defined
384           ; return (op_name, dm, op_ty) }
385
386    mk_doc op_name op_ty = ptext SLIT("Class op") <+> sep [ppr op_name, ppr op_ty]
387
388    tc_fd (tvs1, tvs2) = do { tvs1' <- mappM tcIfaceTyVar tvs1
389                            ; tvs2' <- mappM tcIfaceTyVar tvs2
390                            ; return (tvs1', tvs2') }
391
392 tcIfaceDecl (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
393   = do  { name <- lookupIfaceTop rdr_name
394         ; return (ATyCon (mkForeignTyCon name ext_name 
395                                          liftedTypeKind 0 [])) }
396
397 tcIfaceDataCons tycon tc_tyvars if_cons
398   = case if_cons of
399         IfAbstractTyCon  -> return mkAbstractTyConRhs
400         IfDataTyCon cons -> do  { data_cons <- mappM tc_con_decl cons
401                                 ; return (mkDataTyConRhs data_cons) }
402         IfNewTyCon con   -> do  { data_con <- tc_con_decl con
403                                 ; return (mkNewTyConRhs tycon data_con) }
404   where
405     tc_con_decl (IfVanillaCon { ifConOcc = occ, ifConInfix = is_infix, ifConArgTys = args, 
406                                 ifConStricts = stricts, ifConFields = field_lbls})
407       = do { name  <- lookupIfaceTop occ
408                 -- Read the argument types, but lazily to avoid faulting in
409                 -- the component types unless they are really needed
410            ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
411            ; lbl_names <- mappM lookupIfaceTop field_lbls
412            ; buildDataCon name is_infix True {- Vanilla -} 
413                           stricts lbl_names
414                           tc_tyvars [] arg_tys tycon
415                           (mkTyVarTys tc_tyvars)        -- Vanilla => we know result tys
416            }  
417
418     tc_con_decl (IfGadtCon {    ifConTyVars = con_tvs,
419                                 ifConOcc = occ, ifConCtxt = ctxt, 
420                                 ifConArgTys = args, ifConResTys = ress, 
421                                 ifConStricts = stricts})
422       = bindIfaceTyVars con_tvs $ \ con_tyvars -> do
423         { name  <- lookupIfaceTop occ
424         ; theta <- tcIfaceCtxt ctxt     -- Laziness seems not worth the bother here
425                 -- At one stage I thought that this context checking *had*
426                 -- to be lazy, because of possible mutual recursion between the
427                 -- type and the classe: 
428                 -- E.g. 
429                 --      class Real a where { toRat :: a -> Ratio Integer }
430                 --      data (Real a) => Ratio a = ...
431                 -- But now I think that the laziness in checking class ops breaks 
432                 -- the loop, so no laziness needed
433
434         -- Read the argument types, but lazily to avoid faulting in
435         -- the component types unless they are really needed
436         ; arg_tys <- forkM (mk_doc name) (mappM tcIfaceType args)
437         ; res_tys <- forkM (mk_doc name) (mappM tcIfaceType ress)
438
439         ; buildDataCon name False {- Not infix -} False {- Not vanilla -}
440                        stricts [{- No fields -}]
441                        con_tyvars theta 
442                        arg_tys tycon res_tys
443         }
444     mk_doc con_name = ptext SLIT("Constructor") <+> ppr con_name
445 \end{code}      
446
447
448 %************************************************************************
449 %*                                                                      *
450                 Instances
451 %*                                                                      *
452 %************************************************************************
453
454 \begin{code}
455 tcIfaceInst :: IfaceInst -> IfL Instance
456 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
457                          ifInstCls = cls, ifInstTys = mb_tcs,
458                          ifInstOrph = orph })
459   = do  { dfun    <- forkM (ptext SLIT("Dict fun") <+> ppr dfun_occ) $
460                      tcIfaceExtId (LocalTop dfun_occ)
461         ; cls'    <- lookupIfaceExt cls
462         ; mb_tcs' <- mapM do_tc mb_tcs
463         ; return (mkImportedInstance cls' mb_tcs' orph dfun oflag) }
464   where
465     do_tc Nothing   = return Nothing
466     do_tc (Just tc) = do { tc' <- lookupIfaceTc tc; return (Just tc') }
467 \end{code}
468
469
470 %************************************************************************
471 %*                                                                      *
472                 Rules
473 %*                                                                      *
474 %************************************************************************
475
476 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
477 are in the type environment.  However, remember that typechecking a Rule may 
478 (as a side effect) augment the type envt, and so we may need to iterate the process.
479
480 \begin{code}
481 tcIfaceRule :: IfaceRule -> IfL CoreRule
482 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
483                         ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
484                         ifRuleOrph = orph })
485   = do  { fn' <- lookupIfaceExt fn
486         ; ~(bndrs', args', rhs') <- 
487                 -- Typecheck the payload lazily, in the hope it'll never be looked at
488                 forkM (ptext SLIT("Rule") <+> ftext name) $
489                 bindIfaceBndrs bndrs                      $ \ bndrs' ->
490                 do { args' <- mappM tcIfaceExpr args
491                    ; rhs'  <- tcIfaceExpr rhs
492                    ; return (bndrs', args', rhs') }
493         ; mb_tcs <- mapM ifTopFreeName args
494         ; returnM (Rule { ru_name = name, ru_fn = fn', ru_act = act, 
495                           ru_bndrs = bndrs', ru_args = args', 
496                           ru_rhs = rhs', ru_orph = orph,
497                           ru_rough = mb_tcs,
498                           ru_local = isLocalIfaceExtName fn }) }
499   where
500         -- This function *must* mirror exactly what Rules.topFreeName does
501         -- We could have stored the ru_rough field in the iface file
502         -- but that would be redundant, I think.
503         -- The only wrinkle is that we must not be deceived by
504         -- type syononyms at the top of a type arg.  Since
505         -- we can't tell at this point, we are careful not
506         -- to write them out in coreRuleToIfaceRule
507     ifTopFreeName :: IfaceExpr -> IfL (Maybe Name)
508     ifTopFreeName (IfaceType (IfaceTyConApp tc _ ))
509         = do { n <- lookupIfaceTc tc
510              ; return (Just n) }
511     ifTopFreeName (IfaceApp f a) = ifTopFreeName f
512     ifTopFreeName (IfaceExt ext) = do { n <- lookupIfaceExt ext
513                                       ; return (Just n) }
514     ifTopFreeName other = return Nothing
515 \end{code}
516
517
518 %************************************************************************
519 %*                                                                      *
520                         Types
521 %*                                                                      *
522 %************************************************************************
523
524 \begin{code}
525 tcIfaceType :: IfaceType -> IfL Type
526 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
527 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
528 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
529 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkIfTcApp tc' ts') }
530 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
531 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
532
533 tcIfaceTypes tys = mapM tcIfaceType tys
534
535 mkIfTcApp :: TyCon -> [Type] -> Type
536 -- In interface files we retain type synonyms (for brevity and better error
537 -- messages), but type synonyms can expand into non-hoisted types (ones with
538 -- foralls to the right of an arrow), so we must be careful to hoist them here.
539 -- This hack should go away when we get rid of hoisting.
540 -- Then we should go back to mkGenTyConApp or something like it
541 mkIfTcApp tc tys
542   | isSynTyCon tc = hoistForAllTys (mkSynTy tc tys)
543   | otherwise     = mkTyConApp tc tys
544
545 -----------------------------------------
546 tcIfacePredType :: IfacePredType -> IfL PredType
547 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
548 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
549
550 -----------------------------------------
551 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
552 tcIfaceCtxt sts = mappM tcIfacePredType sts
553 \end{code}
554
555
556 %************************************************************************
557 %*                                                                      *
558                         Core
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
564 tcIfaceExpr (IfaceType ty)
565   = tcIfaceType ty              `thenM` \ ty' ->
566     returnM (Type ty')
567
568 tcIfaceExpr (IfaceLcl name)
569   = tcIfaceLclId name   `thenM` \ id ->
570     returnM (Var id)
571
572 tcIfaceExpr (IfaceExt gbl)
573   = tcIfaceExtId gbl    `thenM` \ id ->
574     returnM (Var id)
575
576 tcIfaceExpr (IfaceLit lit)
577   = returnM (Lit lit)
578
579 tcIfaceExpr (IfaceFCall cc ty)
580   = tcIfaceType ty      `thenM` \ ty' ->
581     newUnique           `thenM` \ u ->
582     returnM (Var (mkFCallId u cc ty'))
583
584 tcIfaceExpr (IfaceTuple boxity args) 
585   = mappM tcIfaceExpr args      `thenM` \ args' ->
586     let
587         -- Put the missing type arguments back in
588         con_args = map (Type . exprType) args' ++ args'
589     in
590     returnM (mkApps (Var con_id) con_args)
591   where
592     arity = length args
593     con_id = dataConWorkId (tupleCon boxity arity)
594     
595
596 tcIfaceExpr (IfaceLam bndr body)
597   = bindIfaceBndr bndr          $ \ bndr' ->
598     tcIfaceExpr body            `thenM` \ body' ->
599     returnM (Lam bndr' body')
600
601 tcIfaceExpr (IfaceApp fun arg)
602   = tcIfaceExpr fun             `thenM` \ fun' ->
603     tcIfaceExpr arg             `thenM` \ arg' ->
604     returnM (App fun' arg')
605
606 tcIfaceExpr (IfaceCase scrut case_bndr ty alts) 
607   = tcIfaceExpr scrut           `thenM` \ scrut' ->
608     newIfaceName case_bndr      `thenM` \ case_bndr_name ->
609     let
610         scrut_ty   = exprType scrut'
611         case_bndr' = mkLocalId case_bndr_name scrut_ty
612         tc_app     = splitTyConApp scrut_ty
613                 -- NB: Won't always succeed (polymoprhic case)
614                 --     but won't be demanded in those cases
615                 -- NB: not tcSplitTyConApp; we are looking at Core here
616                 --     look through non-rec newtypes to find the tycon that
617                 --     corresponds to the datacon in this case alternative
618     in
619     extendIfaceIdEnv [case_bndr']       $
620     mappM (tcIfaceAlt tc_app) alts      `thenM` \ alts' ->
621     tcIfaceType ty              `thenM` \ ty' ->
622     returnM (Case scrut' case_bndr' ty' alts')
623
624 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body)
625   = tcIfaceExpr rhs             `thenM` \ rhs' ->
626     bindIfaceId bndr            $ \ bndr' ->
627     tcIfaceExpr body            `thenM` \ body' ->
628     returnM (Let (NonRec bndr' rhs') body')
629
630 tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
631   = bindIfaceIds bndrs          $ \ bndrs' ->
632     mappM tcIfaceExpr rhss      `thenM` \ rhss' ->
633     tcIfaceExpr body            `thenM` \ body' ->
634     returnM (Let (Rec (bndrs' `zip` rhss')) body')
635   where
636     (bndrs, rhss) = unzip pairs
637
638 tcIfaceExpr (IfaceNote note expr) 
639   = tcIfaceExpr expr            `thenM` \ expr' ->
640     case note of
641         IfaceCoerce to_ty -> tcIfaceType to_ty  `thenM` \ to_ty' ->
642                              returnM (Note (Coerce to_ty'
643                                                    (exprType expr')) expr')
644         IfaceInlineCall   -> returnM (Note InlineCall expr')
645         IfaceInlineMe     -> returnM (Note InlineMe   expr')
646         IfaceSCC cc       -> returnM (Note (SCC cc)   expr')
647         IfaceCoreNote n   -> returnM (Note (CoreNote n) expr')
648
649 -------------------------
650 tcIfaceAlt _ (IfaceDefault, names, rhs)
651   = ASSERT( null names )
652     tcIfaceExpr rhs             `thenM` \ rhs' ->
653     returnM (DEFAULT, [], rhs')
654   
655 tcIfaceAlt _ (IfaceLitAlt lit, names, rhs)
656   = ASSERT( null names )
657     tcIfaceExpr rhs             `thenM` \ rhs' ->
658     returnM (LitAlt lit, [], rhs')
659
660 -- A case alternative is made quite a bit more complicated
661 -- by the fact that we omit type annotations because we can
662 -- work them out.  True enough, but its not that easy!
663 tcIfaceAlt (tycon, inst_tys) (IfaceDataAlt data_occ, arg_occs, rhs)
664   = do  { let tycon_mod = nameModule (tyConName tycon)
665         ; con <- tcIfaceDataCon (ExtPkg tycon_mod data_occ)
666         ; ASSERT2( con `elem` tyConDataCons tycon,
667                    ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon) )
668                   
669           if isVanillaDataCon con then
670                 tcVanillaAlt con inst_tys arg_occs rhs
671           else
672     do  {       -- General case
673           arg_names <- newIfaceNames arg_occs
674         ; let   tyvars   = [ mkTyVar name (tyVarKind tv) 
675                            | (name,tv) <- arg_names `zip` dataConTyVars con] 
676                 arg_tys  = dataConArgTys con (mkTyVarTys tyvars)
677                 id_names = dropList tyvars arg_names
678                 arg_ids  = ASSERT2( equalLength id_names arg_tys,
679                                     ppr (con, arg_names, rhs) $$ ppr tyvars $$ ppr arg_tys )
680                            zipWith mkLocalId id_names arg_tys
681
682         ; rhs' <- extendIfaceTyVarEnv tyvars    $
683                   extendIfaceIdEnv arg_ids      $
684                   tcIfaceExpr rhs
685         ; return (DataAlt con, tyvars ++ arg_ids, rhs') }}
686
687 tcIfaceAlt (tycon, inst_tys) (IfaceTupleAlt boxity, arg_occs, rhs)
688   = ASSERT( isTupleTyCon tycon )
689     do  { let [data_con] = tyConDataCons tycon
690         ; tcVanillaAlt data_con inst_tys arg_occs rhs }
691
692 tcVanillaAlt data_con inst_tys arg_occs rhs
693   = do  { arg_names <- newIfaceNames arg_occs
694         ; let arg_tys = dataConArgTys data_con inst_tys
695         ; let arg_ids = ASSERT2( equalLength arg_names arg_tys,
696                                  ppr data_con <+> ppr inst_tys <+> ppr arg_occs $$ ppr rhs )
697                         zipWith mkLocalId arg_names arg_tys
698         ; rhs' <- extendIfaceIdEnv arg_ids (tcIfaceExpr rhs)
699         ; returnM (DataAlt data_con, arg_ids, rhs') }
700 \end{code}
701
702
703 \begin{code}
704 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind]   -- Used for external core
705 tcExtCoreBindings []     = return []
706 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
707
708 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
709 do_one (IfaceNonRec bndr rhs) thing_inside
710   = do  { rhs' <- tcIfaceExpr rhs
711         ; bndr' <- newExtCoreBndr bndr
712         ; extendIfaceIdEnv [bndr'] $ do 
713         { core_binds <- thing_inside
714         ; return (NonRec bndr' rhs' : core_binds) }}
715
716 do_one (IfaceRec pairs) thing_inside
717   = do  { bndrs' <- mappM newExtCoreBndr bndrs
718         ; extendIfaceIdEnv bndrs' $ do
719         { rhss' <- mappM tcIfaceExpr rhss
720         ; core_binds <- thing_inside
721         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
722   where
723     (bndrs,rhss) = unzip pairs
724 \end{code}
725
726
727 %************************************************************************
728 %*                                                                      *
729                 IdInfo
730 %*                                                                      *
731 %************************************************************************
732
733 \begin{code}
734 tcIdInfo :: Name -> Type -> IfaceIdInfo -> IfL IdInfo
735 tcIdInfo name ty NoInfo         = return vanillaIdInfo
736 tcIdInfo name ty (HasInfo info) = foldlM tcPrag init_info info
737   where
738     -- Set the CgInfo to something sensible but uninformative before
739     -- we start; default assumption is that it has CAFs
740     init_info = vanillaIdInfo
741
742     tcPrag info HsNoCafRefs         = returnM (info `setCafInfo`   NoCafRefs)
743     tcPrag info (HsArity arity)     = returnM (info `setArityInfo` arity)
744     tcPrag info (HsStrictness str)  = returnM (info `setAllStrictnessInfo` Just str)
745
746         -- The next two are lazy, so they don't transitively suck stuff in
747     tcPrag info (HsWorker nm arity) = tcWorkerInfo ty info nm arity
748     tcPrag info (HsUnfold inline_prag expr)
749         = tcPragExpr name expr  `thenM` \ maybe_expr' ->
750           let
751                 -- maybe_expr' doesn't get looked at if the unfolding
752                 -- is never inspected; so the typecheck doesn't even happen
753                 unfold_info = case maybe_expr' of
754                                 Nothing    -> noUnfolding
755                                 Just expr' -> mkTopUnfolding expr' 
756           in
757           returnM (info `setUnfoldingInfoLazily` unfold_info
758                         `setInlinePragInfo`      inline_prag)
759 \end{code}
760
761 \begin{code}
762 tcWorkerInfo ty info wkr arity
763   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
764
765         -- We return without testing maybe_wkr_id, but as soon as info is
766         -- looked at we will test it.  That's ok, because its outside the
767         -- knot; and there seems no big reason to further defer the
768         -- tcIfaceId lookup.  (Contrast with tcPragExpr, where postponing walking
769         -- over the unfolding until it's actually used does seem worth while.)
770         ; us <- newUniqueSupply
771
772         ; returnM (case mb_wkr_id of
773                      Nothing     -> info
774                      Just wkr_id -> add_wkr_info us wkr_id info) }
775   where
776     doc = text "Worker for" <+> ppr wkr
777     add_wkr_info us wkr_id info
778         = info `setUnfoldingInfoLazily`  mk_unfolding us wkr_id
779                `setWorkerInfo`           HasWorker wkr_id arity
780
781     mk_unfolding us wkr_id = mkTopUnfolding (initUs_ us (mkWrapper ty strict_sig) wkr_id)
782
783         -- We are relying here on strictness info always appearing 
784         -- before worker info,  fingers crossed ....
785     strict_sig = case newStrictnessInfo info of
786                    Just sig -> sig
787                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr)
788 \end{code}
789
790 For unfoldings we try to do the job lazily, so that we never type check
791 an unfolding that isn't going to be looked at.
792
793 \begin{code}
794 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
795 tcPragExpr name expr
796   = forkM_maybe doc $
797     tcIfaceExpr expr            `thenM` \ core_expr' ->
798
799                 -- Check for type consistency in the unfolding
800     ifOptM Opt_DoCoreLinting (
801         get_in_scope_ids                        `thenM` \ in_scope -> 
802         case lintUnfolding noSrcLoc in_scope core_expr' of
803           Nothing       -> returnM ()
804           Just fail_msg -> pprPanic "Iface Lint failure" (doc <+> fail_msg)
805     )                           `thenM_`
806
807    returnM core_expr'   
808   where
809     doc = text "Unfolding of" <+> ppr name
810     get_in_scope_ids    -- Urgh; but just for linting
811         = setLclEnv () $ 
812           do    { env <- getGblEnv 
813                 ; case if_rec_types env of {
814                           Nothing -> return [] ;
815                           Just (_, get_env) -> do
816                 { type_env <- get_env
817                 ; return (typeEnvIds type_env) }}}
818 \end{code}
819
820
821
822 %************************************************************************
823 %*                                                                      *
824                 Getting from Names to TyThings
825 %*                                                                      *
826 %************************************************************************
827
828 \begin{code}
829 tcIfaceGlobal :: Name -> IfL TyThing
830 tcIfaceGlobal name
831   | Just thing <- wiredInNameTyThing_maybe name
832         -- Wired-in things include TyCons, DataCons, and Ids
833   = do { loadWiredInHomeIface name; return thing }
834         -- Even though we are in an interface file, we want to make
835         -- sure its instances are loaded (imagine f :: Double -> Double)
836         -- and its RULES are loaded too
837   | otherwise
838   = do  { (eps,hpt) <- getEpsAndHpt
839         ; case lookupType hpt (eps_PTE eps) name of {
840             Just thing -> return thing ;
841             Nothing    -> do
842
843         { env <- getGblEnv
844         ; case if_rec_types env of {
845             Just (mod, get_type_env) 
846                 | nameIsLocalOrFrom mod name
847                 -> do           -- It's defined in the module being compiled
848                 { type_env <- setLclEnv () get_type_env         -- yuk
849                 ; case lookupNameEnv type_env name of
850                         Just thing -> return thing
851                         Nothing    -> pprPanic "tcIfaceGlobal (local): not found:"  
852                                                 (ppr name $$ ppr type_env) }
853
854           ; other -> do
855
856         { mb_thing <- importDecl name   -- It's imported; go get it
857         ; case mb_thing of
858             Failed err      -> failIfM err
859             Succeeded thing -> return thing
860     }}}}}
861
862 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
863 tcIfaceTyCon IfaceIntTc         = tcWiredInTyCon intTyCon
864 tcIfaceTyCon IfaceBoolTc        = tcWiredInTyCon boolTyCon
865 tcIfaceTyCon IfaceCharTc        = tcWiredInTyCon charTyCon
866 tcIfaceTyCon IfaceListTc        = tcWiredInTyCon listTyCon
867 tcIfaceTyCon IfacePArrTc        = tcWiredInTyCon parrTyCon
868 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
869 tcIfaceTyCon (IfaceTc ext_nm)   = do { name <- lookupIfaceExt ext_nm
870                                      ; thing <- tcIfaceGlobal name 
871                                      ; return (check_tc (tyThingTyCon thing)) }
872   where
873 #ifdef DEBUG
874     check_tc tc = case toIfaceTyCon (error "urk") tc of
875                    IfaceTc _ -> tc
876                    other     -> pprTrace "check_tc" (ppr tc) tc
877 #else
878     check_tc tc = tc
879 #endif
880
881 -- Even though we are in an interface file, we want to make
882 -- sure the instances and RULES of this tycon are loaded 
883 -- Imagine: f :: Double -> Double
884 tcWiredInTyCon :: TyCon -> IfL TyCon
885 tcWiredInTyCon tc = do { loadWiredInHomeIface (tyConName tc)
886                        ; return tc }
887
888 tcIfaceClass :: IfaceExtName -> IfL Class
889 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
890                            ; thing <- tcIfaceGlobal name
891                            ; return (tyThingClass thing) }
892
893 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
894 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
895                         ; thing <- tcIfaceGlobal name
896                         ; case thing of
897                                 ADataCon dc -> return dc
898                                 other   -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
899
900 tcIfaceExtId :: IfaceExtName -> IfL Id
901 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
902                       ; thing <- tcIfaceGlobal name
903                       ; case thing of
904                           AnId id -> return id
905                           other   -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
906 \end{code}
907
908 %************************************************************************
909 %*                                                                      *
910                 Bindings
911 %*                                                                      *
912 %************************************************************************
913
914 \begin{code}
915 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
916 bindIfaceBndr (IfaceIdBndr bndr) thing_inside
917   = bindIfaceId bndr thing_inside
918 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
919   = bindIfaceTyVar bndr thing_inside
920     
921 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
922 bindIfaceBndrs []     thing_inside = thing_inside []
923 bindIfaceBndrs (b:bs) thing_inside
924   = bindIfaceBndr b     $ \ b' ->
925     bindIfaceBndrs bs   $ \ bs' ->
926     thing_inside (b':bs')
927
928 -----------------------
929 bindIfaceId :: (OccName, IfaceType) -> (Id -> IfL a) -> IfL a
930 bindIfaceId (occ, ty) thing_inside
931   = do  { name <- newIfaceName occ
932         ; ty' <- tcIfaceType ty
933         ; let { id = mkLocalId name ty' }
934         ; extendIfaceIdEnv [id] (thing_inside id) }
935     
936 bindIfaceIds :: [(OccName, IfaceType)] -> ([Id] -> IfL a) -> IfL a
937 bindIfaceIds bndrs thing_inside
938   = do  { names <- newIfaceNames occs
939         ; tys' <- mappM tcIfaceType tys
940         ; let { ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys' }
941         ; extendIfaceIdEnv ids (thing_inside ids) }
942   where
943     (occs,tys) = unzip bndrs
944
945
946 -----------------------
947 newExtCoreBndr :: (OccName, IfaceType) -> IfL Id
948 newExtCoreBndr (occ, ty)
949   = do  { mod <- getIfModule
950         ; name <- newGlobalBinder mod occ Nothing noSrcLoc
951         ; ty' <- tcIfaceType ty
952         ; return (mkLocalId name ty') }
953
954 -----------------------
955 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
956 bindIfaceTyVar (occ,kind) thing_inside
957   = do  { name <- newIfaceName occ
958         ; let tyvar = mk_iface_tyvar name kind
959         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
960
961 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
962 bindIfaceTyVars bndrs thing_inside
963   = do  { names <- newIfaceNames occs
964         ; let tyvars = zipWith mk_iface_tyvar names kinds
965         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
966   where
967     (occs,kinds) = unzip bndrs
968
969 mk_iface_tyvar name kind = mkTyVar name kind
970 \end{code}
971