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