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