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