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