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