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