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