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