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