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