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