The Big INLINE Patch: totally reorganise way that INLINE pragmas work
[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,
12         tcIfaceVectInfo, tcIfaceAnnotations, tcIfaceGlobal, 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 TcType
23 import Type
24 import TypeRep
25 import HscTypes
26 import Annotations
27 import InstEnv
28 import FamInstEnv
29 import CoreSyn
30 import CoreUtils
31 import CoreUnfold
32 import CoreLint
33 import WorkWrap
34 import Id
35 import MkId
36 import IdInfo
37 import Class
38 import TyCon
39 import DataCon
40 import TysWiredIn
41 import TysPrim          ( anyTyConOfKind )
42 import Var              ( TyVar )
43 import qualified Var
44 import VarEnv
45 import Name
46 import NameEnv
47 import OccurAnal        ( occurAnalyseExpr )
48 import Module
49 import LazyUniqFM
50 import UniqSupply
51 import Outputable       
52 import ErrUtils
53 import Maybes
54 import SrcLoc
55 import DynFlags
56 import Util
57 import FastString
58
59 import Control.Monad
60 import Data.List
61 \end{code}
62
63 This module takes
64
65         IfaceDecl -> TyThing
66         IfaceType -> Type
67         etc
68
69 An IfaceDecl is populated with RdrNames, and these are not renamed to
70 Names before typechecking, because there should be no scope errors etc.
71
72         -- For (b) consider: f = \$(...h....)
73         -- where h is imported, and calls f via an hi-boot file.  
74         -- This is bad!  But it is not seen as a staging error, because h
75         -- is indeed imported.  We don't want the type-checker to black-hole 
76         -- when simplifying and compiling the splice!
77         --
78         -- Simple solution: discard any unfolding that mentions a variable
79         -- bound in this module (and hence not yet processed).
80         -- The discarding happens when forkM finds a type error.
81
82 %************************************************************************
83 %*                                                                      *
84 %*      tcImportDecl is the key function for "faulting in"              *
85 %*      imported things
86 %*                                                                      *
87 %************************************************************************
88
89 The main idea is this.  We are chugging along type-checking source code, and
90 find a reference to GHC.Base.map.  We call tcLookupGlobal, which doesn't find
91 it in the EPS type envt.  So it 
92         1 loads GHC.Base.hi
93         2 gets the decl for GHC.Base.map
94         3 typechecks it via tcIfaceDecl
95         4 and adds it to the type env in the EPS
96
97 Note that DURING STEP 4, we may find that map's type mentions a type 
98 constructor that also 
99
100 Notice that for imported things we read the current version from the EPS
101 mutable variable.  This is important in situations like
102         ...$(e1)...$(e2)...
103 where the code that e1 expands to might import some defns that 
104 also turn out to be needed by the code that e2 expands to.
105
106 \begin{code}
107 tcImportDecl :: Name -> TcM TyThing
108 -- Entry point for *source-code* uses of importDecl
109 tcImportDecl name 
110   | Just thing <- wiredInNameTyThing_maybe name
111   = do  { when (needWiredInHomeIface thing)
112                (initIfaceTcRn (loadWiredInHomeIface name))
113                 -- See Note [Loading instances for wired-in things]
114         ; return thing }
115   | otherwise
116   = do  { traceIf (text "tcImportDecl" <+> ppr name)
117         ; mb_thing <- initIfaceTcRn (importDecl name)
118         ; case mb_thing of
119             Succeeded thing -> return thing
120             Failed err      -> failWithTc err }
121
122 importDecl :: Name -> IfM lcl (MaybeErr Message TyThing)
123 -- Get the TyThing for this Name from an interface file
124 -- It's not a wired-in thing -- the caller caught that
125 importDecl name
126   = ASSERT( not (isWiredInName name) )
127     do  { traceIf nd_doc
128
129         -- Load the interface, which should populate the PTE
130         ; mb_iface <- ASSERT2( isExternalName name, ppr name ) 
131                       loadInterface nd_doc (nameModule name) ImportBySystem
132         ; case mb_iface of {
133                 Failed err_msg  -> return (Failed err_msg) ;
134                 Succeeded _ -> do
135
136         -- Now look it up again; this time we should find it
137         { eps <- getEps 
138         ; case lookupTypeEnv (eps_PTE eps) name of
139             Just thing -> return (Succeeded thing)
140             Nothing    -> return (Failed not_found_msg)
141     }}}
142   where
143     nd_doc = ptext (sLit "Need decl for") <+> ppr name
144     not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
145                                 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
146                        2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
147                                 ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
148 \end{code}
149
150 %************************************************************************
151 %*                                                                      *
152            Checks for wired-in things
153 %*                                                                      *
154 %************************************************************************
155
156 Note [Loading instances for wired-in things]
157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158 We need to make sure that we have at least *read* the interface files
159 for any module with an instance decl or RULE that we might want.  
160
161 * If the instance decl is an orphan, we have a whole separate mechanism
162   (loadOprhanModules)
163
164 * If the instance decl not an orphan, then the act of looking at the
165   TyCon or Class will force in the defining module for the
166   TyCon/Class, and hence the instance decl
167
168 * BUT, if the TyCon is a wired-in TyCon, we don't really need its interface;
169   but we must make sure we read its interface in case it has instances or
170   rules.  That is what LoadIface.loadWiredInHomeInterface does.  It's called
171   from TcIface.{tcImportDecl, checkWiredInTyCon, ifCheckWiredInThing}
172
173 * HOWEVER, only do this for TyCons.  There are no wired-in Classes.  There
174   are some wired-in Ids, but we don't want to load their interfaces. For
175   example, Control.Exception.Base.recSelError is wired in, but that module
176   is compiled late in the base library, and we don't want to force it to
177   load before it's been compiled!
178
179 All of this is done by the type checker. The renamer plays no role.
180 (It used to, but no longer.)
181
182
183 \begin{code}
184 checkWiredInTyCon :: TyCon -> TcM ()
185 -- Ensure that the home module of the TyCon (and hence its instances)
186 -- are loaded. See Note [Loading instances for wired-in things]
187 -- It might not be a wired-in tycon (see the calls in TcUnify),
188 -- in which case this is a no-op.
189 checkWiredInTyCon tc    
190   | not (isWiredInName tc_name) 
191   = return ()
192   | otherwise
193   = do  { mod <- getModule
194         ; ASSERT( isExternalName tc_name ) 
195           when (mod /= nameModule tc_name)
196                (initIfaceTcRn (loadWiredInHomeIface tc_name))
197                 -- Don't look for (non-existent) Float.hi when
198                 -- compiling Float.lhs, which mentions Float of course
199                 -- A bit yukky to call initIfaceTcRn here
200         }
201   where
202     tc_name = tyConName tc
203
204 ifCheckWiredInThing :: TyThing -> IfL ()
205 -- Even though we are in an interface file, we want to make
206 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
207 -- Ditto want to ensure that RULES are loaded too
208 -- See Note [Loading instances for wired-in things]
209 ifCheckWiredInThing thing
210   = do  { mod <- getIfModule
211                 -- Check whether we are typechecking the interface for this
212                 -- very module.  E.g when compiling the base library in --make mode
213                 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
214                 -- the HPT, so without the test we'll demand-load it into the PIT!
215                 -- C.f. the same test in checkWiredInTyCon above
216         ; let name = getName thing
217         ; ASSERT2( isExternalName name, ppr name ) 
218           when (needWiredInHomeIface thing && mod /= nameModule name)
219                (loadWiredInHomeIface name) }
220
221 needWiredInHomeIface :: TyThing -> Bool
222 -- Only for TyCons; see Note [Loading instances for wired-in things]
223 needWiredInHomeIface (ATyCon {}) = True
224 needWiredInHomeIface _           = False
225 \end{code}
226
227 %************************************************************************
228 %*                                                                      *
229                 Type-checking a complete interface
230 %*                                                                      *
231 %************************************************************************
232
233 Suppose we discover we don't need to recompile.  Then we must type
234 check the old interface file.  This is a bit different to the
235 incremental type checking we do as we suck in interface files.  Instead
236 we do things similarly as when we are typechecking source decls: we
237 bring into scope the type envt for the interface all at once, using a
238 knot.  Remember, the decls aren't necessarily in dependency order --
239 and even if they were, the type decls might be mutually recursive.
240
241 \begin{code}
242 typecheckIface :: ModIface      -- Get the decls from here
243                -> TcRnIf gbl lcl ModDetails
244 typecheckIface iface
245   = initIfaceTc iface $ \ tc_env_var -> do
246         -- The tc_env_var is freshly allocated, private to 
247         -- type-checking this particular interface
248         {       -- Get the right set of decls and rules.  If we are compiling without -O
249                 -- we discard pragmas before typechecking, so that we don't "see"
250                 -- information that we shouldn't.  From a versioning point of view
251                 -- It's not actually *wrong* to do so, but in fact GHCi is unable 
252                 -- to handle unboxed tuples, so it must not see unfoldings.
253           ignore_prags <- doptM Opt_IgnoreInterfacePragmas
254
255                 -- Typecheck the decls.  This is done lazily, so that the knot-tying
256                 -- within this single module work out right.  In the If monad there is
257                 -- no global envt for the current interface; instead, the knot is tied
258                 -- through the if_rec_types field of IfGblEnv
259         ; names_w_things <- loadDecls ignore_prags (mi_decls iface)
260         ; let type_env = mkNameEnv names_w_things
261         ; writeMutVar tc_env_var type_env
262
263                 -- Now do those rules, instances and annotations
264         ; insts     <- mapM tcIfaceInst    (mi_insts     iface)
265         ; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
266         ; rules     <- tcIfaceRules ignore_prags (mi_rules iface)
267         ; anns      <- tcIfaceAnnotations  (mi_anns iface)
268
269                 -- Vectorisation information
270         ; vect_info <- tcIfaceVectInfo (mi_module iface) type_env 
271                                        (mi_vect_info iface)
272
273                 -- Exports
274         ; exports <- ifaceExportNames (mi_exports iface)
275
276                 -- Finished
277         ; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
278                          text "Type envt:" <+> ppr type_env])
279         ; return $ ModDetails { md_types     = type_env
280                               , md_insts     = insts
281                               , md_fam_insts = fam_insts
282                               , md_rules     = rules
283                               , md_anns      = anns
284                               , md_vect_info = vect_info
285                               , md_exports   = exports
286                               }
287     }
288 \end{code}
289
290
291 %************************************************************************
292 %*                                                                      *
293                 Type and class declarations
294 %*                                                                      *
295 %************************************************************************
296
297 \begin{code}
298 tcHiBootIface :: HscSource -> Module -> TcRn ModDetails
299 -- Load the hi-boot iface for the module being compiled,
300 -- if it indeed exists in the transitive closure of imports
301 -- Return the ModDetails, empty if no hi-boot iface
302 tcHiBootIface hsc_src mod
303   | isHsBoot hsc_src            -- Already compiling a hs-boot file
304   = return emptyModDetails
305   | otherwise
306   = do  { traceIf (text "loadHiBootInterface" <+> ppr mod)
307
308         ; mode <- getGhcMode
309         ; if not (isOneShot mode)
310                 -- In --make and interactive mode, if this module has an hs-boot file
311                 -- we'll have compiled it already, and it'll be in the HPT
312                 -- 
313                 -- We check wheher the interface is a *boot* interface.
314                 -- It can happen (when using GHC from Visual Studio) that we
315                 -- compile a module in TypecheckOnly mode, with a stable, 
316                 -- fully-populated HPT.  In that case the boot interface isn't there
317                 -- (it's been replaced by the mother module) so we can't check it.
318                 -- And that's fine, because if M's ModInfo is in the HPT, then 
319                 -- it's been compiled once, and we don't need to check the boot iface
320           then do { hpt <- getHpt
321                   ; case lookupUFM hpt (moduleName mod) of
322                       Just info | mi_boot (hm_iface info) 
323                                 -> return (hm_details info)
324                       _ -> return emptyModDetails }
325           else do
326
327         -- OK, so we're in one-shot mode.  
328         -- In that case, we're read all the direct imports by now, 
329         -- so eps_is_boot will record if any of our imports mention us by 
330         -- way of hi-boot file
331         { eps <- getEps
332         ; case lookupUFM (eps_is_boot eps) (moduleName mod) of {
333             Nothing -> return emptyModDetails ; -- The typical case
334
335             Just (_, False) -> failWithTc moduleLoop ;
336                 -- Someone below us imported us!
337                 -- This is a loop with no hi-boot in the way
338                 
339             Just (_mod, True) ->        -- There's a hi-boot interface below us
340                 
341     do  { read_result <- findAndReadIface 
342                                 need mod
343                                 True    -- Hi-boot file
344
345         ; case read_result of
346                 Failed err               -> failWithTc (elaborate err)
347                 Succeeded (iface, _path) -> typecheckIface iface
348     }}}}
349   where
350     need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
351                  <+> ptext (sLit "to compare against the Real Thing")
352
353     moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod) 
354                      <+> ptext (sLit "depends on itself")
355
356     elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+> 
357                           quotes (ppr mod) <> colon) 4 err
358 \end{code}
359
360
361 %************************************************************************
362 %*                                                                      *
363                 Type and class declarations
364 %*                                                                      *
365 %************************************************************************
366
367 When typechecking a data type decl, we *lazily* (via forkM) typecheck
368 the constructor argument types.  This is in the hope that we may never
369 poke on those argument types, and hence may never need to load the
370 interface files for types mentioned in the arg types.
371
372 E.g.    
373         data Foo.S = MkS Baz.T
374 Mabye we can get away without even loading the interface for Baz!
375
376 This is not just a performance thing.  Suppose we have
377         data Foo.S = MkS Baz.T
378         data Baz.T = MkT Foo.S
379 (in different interface files, of course).
380 Now, first we load and typecheck Foo.S, and add it to the type envt.  
381 If we do explore MkS's argument, we'll load and typecheck Baz.T.
382 If we explore MkT's argument we'll find Foo.S already in the envt.  
383
384 If we typechecked constructor args eagerly, when loading Foo.S we'd try to
385 typecheck the type Baz.T.  So we'd fault in Baz.T... and then need Foo.S...
386 which isn't done yet.
387
388 All very cunning. However, there is a rather subtle gotcha which bit
389 me when developing this stuff.  When we typecheck the decl for S, we
390 extend the type envt with S, MkS, and all its implicit Ids.  Suppose
391 (a bug, but it happened) that the list of implicit Ids depended in
392 turn on the constructor arg types.  Then the following sequence of
393 events takes place:
394         * we build a thunk <t> for the constructor arg tys
395         * we build a thunk for the extended type environment (depends on <t>)
396         * we write the extended type envt into the global EPS mutvar
397         
398 Now we look something up in the type envt
399         * that pulls on <t>
400         * which reads the global type envt out of the global EPS mutvar
401         * but that depends in turn on <t>
402
403 It's subtle, because, it'd work fine if we typechecked the constructor args 
404 eagerly -- they don't need the extended type envt.  They just get the extended
405 type envt by accident, because they look at it later.
406
407 What this means is that the implicitTyThings MUST NOT DEPEND on any of
408 the forkM stuff.
409
410
411 \begin{code}
412 tcIfaceDecl :: Bool     -- True <=> discard IdInfo on IfaceId bindings
413             -> IfaceDecl
414             -> IfL TyThing
415
416 tcIfaceDecl ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type, 
417                                    ifIdDetails = details, ifIdInfo = info})
418   = do  { name <- lookupIfaceTop occ_name
419         ; ty <- tcIfaceType iface_type
420         ; details <- tcIdDetails ty details
421         ; info <- tcIdInfo ignore_prags name ty info
422         ; return (AnId (mkGlobalId details name ty info)) }
423
424 tcIfaceDecl _ (IfaceData {ifName = occ_name, 
425                           ifTyVars = tv_bndrs, 
426                           ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
427                           ifCons = rdr_cons, 
428                           ifRec = is_rec, 
429                           ifGeneric = want_generic,
430                           ifFamInst = mb_family })
431   = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
432     { tc_name <- lookupIfaceTop occ_name
433     ; tycon <- fixM ( \ tycon -> do
434             { stupid_theta <- tcIfaceCtxt ctxt
435             ; mb_fam_inst  <- tcFamInst mb_family
436             ; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
437             ; buildAlgTyCon tc_name tyvars stupid_theta
438                             cons is_rec want_generic gadt_syn mb_fam_inst
439             })
440     ; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
441     ; return (ATyCon tycon) }
442
443 tcIfaceDecl _ (IfaceSyn {ifName = occ_name, ifTyVars = tv_bndrs, 
444                          ifSynRhs = mb_rhs_ty,
445                          ifSynKind = kind, ifFamInst = mb_family})
446    = bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
447      { tc_name <- lookupIfaceTop occ_name
448      ; rhs_kind <- tcIfaceType kind     -- Note [Synonym kind loop]
449      ; ~(rhs, fam) <- forkM (mk_doc tc_name) $ 
450                       do { rhs <- tc_syn_rhs rhs_kind mb_rhs_ty
451                          ; fam <- tcFamInst mb_family
452                          ; return (rhs, fam) }
453      ; tycon <- buildSynTyCon tc_name tyvars rhs rhs_kind fam
454      ; return $ ATyCon tycon
455      }
456    where
457      mk_doc n = ptext (sLit "Type syonym") <+> ppr n
458      tc_syn_rhs kind Nothing   = return (OpenSynTyCon kind Nothing)
459      tc_syn_rhs _    (Just ty) = do { rhs_ty <- tcIfaceType ty
460                                     ; return (SynonymTyCon rhs_ty) }
461
462 tcIfaceDecl ignore_prags
463             (IfaceClass {ifCtxt = rdr_ctxt, ifName = occ_name, 
464                          ifTyVars = tv_bndrs, ifFDs = rdr_fds, 
465                          ifATs = rdr_ats, ifSigs = rdr_sigs, 
466                          ifRec = tc_isrec })
467 -- ToDo: in hs-boot files we should really treat abstract classes specially,
468 --       as we do abstract tycons
469   = bindIfaceTyVars tv_bndrs $ \ tyvars -> do
470     { cls_name <- lookupIfaceTop occ_name
471     ; ctxt <- tcIfaceCtxt rdr_ctxt
472     ; sigs <- mapM tc_sig rdr_sigs
473     ; fds  <- mapM tc_fd rdr_fds
474     ; ats' <- mapM (tcIfaceDecl ignore_prags) rdr_ats
475     ; let ats = map (setAssocFamilyPermutation tyvars) ats'
476     ; cls  <- buildClass ignore_prags cls_name tyvars ctxt fds ats sigs tc_isrec
477     ; return (AClass cls) }
478   where
479    tc_sig (IfaceClassOp occ dm rdr_ty)
480      = do { op_name <- lookupIfaceTop occ
481           ; op_ty   <- forkM (mk_doc op_name rdr_ty) (tcIfaceType rdr_ty)
482                 -- Must be done lazily for just the same reason as the 
483                 -- type of a data con; to avoid sucking in types that
484                 -- it mentions unless it's necessray to do so
485           ; return (op_name, dm, op_ty) }
486
487    mk_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
488
489    tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
490                            ; tvs2' <- mapM tcIfaceTyVar tvs2
491                            ; return (tvs1', tvs2') }
492
493 tcIfaceDecl _ (IfaceForeign {ifName = rdr_name, ifExtName = ext_name})
494   = do  { name <- lookupIfaceTop rdr_name
495         ; return (ATyCon (mkForeignTyCon name ext_name 
496                                          liftedTypeKind 0)) }
497
498 tcFamInst :: Maybe (IfaceTyCon, [IfaceType]) -> IfL (Maybe (TyCon, [Type]))
499 tcFamInst Nothing           = return Nothing
500 tcFamInst (Just (fam, tys)) = do { famTyCon <- tcIfaceTyCon fam
501                                  ; insttys <- mapM tcIfaceType tys
502                                  ; return $ Just (famTyCon, insttys) }
503
504 tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
505 tcIfaceDataCons tycon_name tycon _ if_cons
506   = case if_cons of
507         IfAbstractTyCon  -> return mkAbstractTyConRhs
508         IfOpenDataTyCon  -> return mkOpenDataTyConRhs
509         IfDataTyCon cons -> do  { data_cons <- mapM tc_con_decl cons
510                                 ; return (mkDataTyConRhs data_cons) }
511         IfNewTyCon con   -> do  { data_con <- tc_con_decl con
512                                 ; mkNewTyConRhs tycon_name tycon data_con }
513   where
514     tc_con_decl (IfCon { ifConInfix = is_infix, 
515                          ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
516                          ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
517                          ifConArgTys = args, ifConFields = field_lbls,
518                          ifConStricts = stricts})
519      = bindIfaceTyVars univ_tvs $ \ univ_tyvars -> do
520        bindIfaceTyVars ex_tvs    $ \ ex_tyvars -> do
521         { name  <- lookupIfaceTop occ
522         ; eq_spec <- tcIfaceEqSpec spec
523         ; theta <- tcIfaceCtxt ctxt     -- Laziness seems not worth the bother here
524                 -- At one stage I thought that this context checking *had*
525                 -- to be lazy, because of possible mutual recursion between the
526                 -- type and the classe: 
527                 -- E.g. 
528                 --      class Real a where { toRat :: a -> Ratio Integer }
529                 --      data (Real a) => Ratio a = ...
530                 -- But now I think that the laziness in checking class ops breaks 
531                 -- the loop, so no laziness needed
532
533         -- Read the argument types, but lazily to avoid faulting in
534         -- the component types unless they are really needed
535         ; arg_tys <- forkM (mk_doc name) (mapM tcIfaceType args)
536         ; lbl_names <- mapM lookupIfaceTop field_lbls
537
538         -- Remember, tycon is the representation tycon
539         ; let orig_res_ty = mkFamilyTyConApp tycon 
540                                 (substTyVars (mkTopTvSubst eq_spec) univ_tyvars)
541
542         ; buildDataCon name is_infix {- Not infix -}
543                        stricts lbl_names
544                        univ_tyvars ex_tyvars 
545                        eq_spec theta 
546                        arg_tys orig_res_ty tycon
547         }
548     mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
549
550 tcIfaceEqSpec :: [(OccName, IfaceType)] -> IfL [(TyVar, Type)]
551 tcIfaceEqSpec spec
552   = mapM do_item spec
553   where
554     do_item (occ, if_ty) = do { tv <- tcIfaceTyVar (occNameFS occ)
555                               ; ty <- tcIfaceType if_ty
556                               ; return (tv,ty) }
557 \end{code}
558
559 Note [Synonym kind loop]
560 ~~~~~~~~~~~~~~~~~~~~~~~~
561 Notice that we eagerly grab the *kind* from the interface file, but
562 build a forkM thunk for the *rhs* (and family stuff).  To see why, 
563 consider this (Trac #2412)
564
565 M.hs:       module M where { import X; data T = MkT S }
566 X.hs:       module X where { import {-# SOURCE #-} M; type S = T }
567 M.hs-boot:  module M where { data T }
568
569 When kind-checking M.hs we need S's kind.  But we do not want to
570 find S's kind from (typeKind S-rhs), because we don't want to look at
571 S-rhs yet!  Since S is imported from X.hi, S gets just one chance to
572 be defined, and we must not do that until we've finished with M.T.
573
574 Solution: record S's kind in the interface file; now we can safely
575 look at it.
576
577 %************************************************************************
578 %*                                                                      *
579                 Instances
580 %*                                                                      *
581 %************************************************************************
582
583 \begin{code}
584 tcIfaceInst :: IfaceInst -> IfL Instance
585 tcIfaceInst (IfaceInst { ifDFun = dfun_occ, ifOFlag = oflag,
586                          ifInstCls = cls, ifInstTys = mb_tcs })
587   = do  { dfun    <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
588                      tcIfaceExtId dfun_occ
589         ; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
590         ; return (mkImportedInstance cls mb_tcs' dfun oflag) }
591
592 tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
593 tcIfaceFamInst (IfaceFamInst { ifFamInstTyCon = tycon, 
594                                ifFamInstFam = fam, ifFamInstTys = mb_tcs })
595 --      { tycon'  <- forkM (ptext (sLit "Inst tycon") <+> ppr tycon) $
596 -- the above line doesn't work, but this below does => CPP in Haskell = evil!
597     = do tycon'  <- forkM (text ("Inst tycon") <+> ppr tycon) $
598                     tcIfaceTyCon tycon
599          let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
600          return (mkImportedFamInst fam mb_tcs' tycon')
601 \end{code}
602
603
604 %************************************************************************
605 %*                                                                      *
606                 Rules
607 %*                                                                      *
608 %************************************************************************
609
610 We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
611 are in the type environment.  However, remember that typechecking a Rule may 
612 (as a side effect) augment the type envt, and so we may need to iterate the process.
613
614 \begin{code}
615 tcIfaceRules :: Bool            -- True <=> ignore rules
616              -> [IfaceRule]
617              -> IfL [CoreRule]
618 tcIfaceRules ignore_prags if_rules
619   | ignore_prags = return []
620   | otherwise    = mapM tcIfaceRule if_rules
621
622 tcIfaceRule :: IfaceRule -> IfL CoreRule
623 tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
624                         ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
625   = do  { ~(bndrs', args', rhs') <- 
626                 -- Typecheck the payload lazily, in the hope it'll never be looked at
627                 forkM (ptext (sLit "Rule") <+> ftext name) $
628                 bindIfaceBndrs bndrs                      $ \ bndrs' ->
629                 do { args' <- mapM tcIfaceExpr args
630                    ; rhs'  <- tcIfaceExpr rhs
631                    ; return (bndrs', args', rhs') }
632         ; let mb_tcs = map ifTopFreeName args
633         ; return (Rule { ru_name = name, ru_fn = fn, ru_act = act, 
634                           ru_bndrs = bndrs', ru_args = args', 
635                           ru_rhs = occurAnalyseExpr rhs', 
636                           ru_rough = mb_tcs,
637                           ru_local = False }) } -- An imported RULE is never for a local Id
638                                                 -- or, even if it is (module loop, perhaps)
639                                                 -- we'll just leave it in the non-local set
640   where
641         -- This function *must* mirror exactly what Rules.topFreeName does
642         -- We could have stored the ru_rough field in the iface file
643         -- but that would be redundant, I think.
644         -- The only wrinkle is that we must not be deceived by
645         -- type syononyms at the top of a type arg.  Since
646         -- we can't tell at this point, we are careful not
647         -- to write them out in coreRuleToIfaceRule
648     ifTopFreeName :: IfaceExpr -> Maybe Name
649     ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
650     ifTopFreeName (IfaceApp f _)                    = ifTopFreeName f
651     ifTopFreeName (IfaceExt n)                      = Just n
652     ifTopFreeName _                                 = Nothing
653 \end{code}
654
655
656 %************************************************************************
657 %*                                                                      *
658                 Annotations
659 %*                                                                      *
660 %************************************************************************
661
662 \begin{code}
663 tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
664 tcIfaceAnnotations = mapM tcIfaceAnnotation
665
666 tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
667 tcIfaceAnnotation (IfaceAnnotation target serialized) = do
668     target' <- tcIfaceAnnTarget target
669     return $ Annotation {
670         ann_target = target',
671         ann_value = serialized
672     }
673
674 tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
675 tcIfaceAnnTarget (NamedTarget occ) = do
676     name <- lookupIfaceTop occ
677     return $ NamedTarget name
678 tcIfaceAnnTarget (ModuleTarget mod) = do
679     return $ ModuleTarget mod
680
681 \end{code}
682
683
684 %************************************************************************
685 %*                                                                      *
686                 Vectorisation information
687 %*                                                                      *
688 %************************************************************************
689
690 \begin{code}
691 tcIfaceVectInfo :: Module -> TypeEnv  -> IfaceVectInfo -> IfL VectInfo
692 tcIfaceVectInfo mod typeEnv (IfaceVectInfo 
693                              { ifaceVectInfoVar        = vars
694                              , ifaceVectInfoTyCon      = tycons
695                              , ifaceVectInfoTyConReuse = tyconsReuse
696                              })
697   = do { vVars     <- mapM vectVarMapping vars
698        ; tyConRes1 <- mapM vectTyConMapping      tycons
699        ; tyConRes2 <- mapM vectTyConReuseMapping tyconsReuse
700        ; let (vTyCons, vDataCons, vPAs, vIsos) = unzip4 (tyConRes1 ++ tyConRes2)
701        ; return $ VectInfo 
702                   { vectInfoVar     = mkVarEnv  vVars
703                   , vectInfoTyCon   = mkNameEnv vTyCons
704                   , vectInfoDataCon = mkNameEnv (concat vDataCons)
705                   , vectInfoPADFun  = mkNameEnv vPAs
706                   , vectInfoIso     = mkNameEnv vIsos
707                   }
708        }
709   where
710     vectVarMapping name 
711       = do { vName <- lookupOrig mod (mkVectOcc (nameOccName name))
712            ; let { var  = lookupVar name
713                  ; vVar = lookupVar vName
714                  }
715            ; return (var, (var, vVar))
716            }
717     vectTyConMapping name 
718       = do { vName   <- lookupOrig mod (mkVectTyConOcc (nameOccName name))
719            ; paName  <- lookupOrig mod (mkPADFunOcc    (nameOccName name))
720            ; isoName <- lookupOrig mod (mkVectIsoOcc   (nameOccName name))
721            ; let { tycon    = lookupTyCon name
722                  ; vTycon   = lookupTyCon vName
723                  ; paTycon  = lookupVar paName
724                  ; isoTycon = lookupVar isoName
725                  }
726            ; vDataCons <- mapM vectDataConMapping (tyConDataCons tycon)
727            ; return ((name, (tycon, vTycon)),    -- (T, T_v)
728                      vDataCons,                  -- list of (Ci, Ci_v)
729                      (vName, (vTycon, paTycon)), -- (T_v, paT)
730                      (name, (tycon, isoTycon)))  -- (T, isoT)
731            }
732     vectTyConReuseMapping name 
733       = do { paName  <- lookupOrig mod (mkPADFunOcc    (nameOccName name))
734            ; isoName <- lookupOrig mod (mkVectIsoOcc   (nameOccName name))
735            ; let { tycon      = lookupTyCon name
736                  ; paTycon    = lookupVar paName
737                  ; isoTycon   = lookupVar isoName
738                  ; vDataCons  = [ (dataConName dc, (dc, dc)) 
739                                 | dc <- tyConDataCons tycon]
740                  }
741            ; return ((name, (tycon, tycon)),     -- (T, T)
742                      vDataCons,                  -- list of (Ci, Ci)
743                      (name, (tycon, paTycon)),   -- (T, paT)
744                      (name, (tycon, isoTycon)))  -- (T, isoT)
745            }
746     vectDataConMapping datacon
747       = do { let name = dataConName datacon
748            ; vName <- lookupOrig mod (mkVectDataConOcc (nameOccName name))
749            ; let vDataCon = lookupDataCon vName
750            ; return (name, (datacon, vDataCon))
751            }
752     --
753     lookupVar name = case lookupTypeEnv typeEnv name of
754                        Just (AnId var) -> var
755                        Just _         -> 
756                          panic "TcIface.tcIfaceVectInfo: not an id"
757                        Nothing        ->
758                          panic "TcIface.tcIfaceVectInfo: unknown name"
759     lookupTyCon name = case lookupTypeEnv typeEnv name of
760                          Just (ATyCon tc) -> tc
761                          Just _         -> 
762                            panic "TcIface.tcIfaceVectInfo: not a tycon"
763                          Nothing        ->
764                            panic "TcIface.tcIfaceVectInfo: unknown name"
765     lookupDataCon name = case lookupTypeEnv typeEnv name of
766                            Just (ADataCon dc) -> dc
767                            Just _         -> 
768                              panic "TcIface.tcIfaceVectInfo: not a datacon"
769                            Nothing        ->
770                              panic "TcIface.tcIfaceVectInfo: unknown name"
771 \end{code}
772
773 %************************************************************************
774 %*                                                                      *
775                         Types
776 %*                                                                      *
777 %************************************************************************
778
779 \begin{code}
780 tcIfaceType :: IfaceType -> IfL Type
781 tcIfaceType (IfaceTyVar n)        = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
782 tcIfaceType (IfaceAppTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
783 tcIfaceType (IfaceFunTy t1 t2)    = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
784 tcIfaceType (IfaceTyConApp tc ts) = do { tc' <- tcIfaceTyCon tc; ts' <- tcIfaceTypes ts; return (mkTyConApp tc' ts') }
785 tcIfaceType (IfaceForAllTy tv t)  = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
786 tcIfaceType (IfacePredTy st)      = do { st' <- tcIfacePredType st; return (PredTy st') }
787
788 tcIfaceTypes :: [IfaceType] -> IfL [Type]
789 tcIfaceTypes tys = mapM tcIfaceType tys
790
791 -----------------------------------------
792 tcIfacePredType :: IfacePredType -> IfL PredType
793 tcIfacePredType (IfaceClassP cls ts) = do { cls' <- tcIfaceClass cls; ts' <- tcIfaceTypes ts; return (ClassP cls' ts') }
794 tcIfacePredType (IfaceIParam ip t)   = do { ip' <- newIPName ip; t' <- tcIfaceType t; return (IParam ip' t') }
795 tcIfacePredType (IfaceEqPred t1 t2)  = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (EqPred t1' t2') }
796
797 -----------------------------------------
798 tcIfaceCtxt :: IfaceContext -> IfL ThetaType
799 tcIfaceCtxt sts = mapM tcIfacePredType sts
800 \end{code}
801
802
803 %************************************************************************
804 %*                                                                      *
805                         Core
806 %*                                                                      *
807 %************************************************************************
808
809 \begin{code}
810 tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
811 tcIfaceExpr (IfaceType ty)
812   = Type <$> tcIfaceType ty
813
814 tcIfaceExpr (IfaceLcl name)
815   = Var <$> tcIfaceLclId name
816
817 tcIfaceExpr (IfaceTick modName tickNo)
818   = Var <$> tcIfaceTick modName tickNo
819
820 tcIfaceExpr (IfaceExt gbl)
821   = Var <$> tcIfaceExtId gbl
822
823 tcIfaceExpr (IfaceLit lit)
824   = return (Lit lit)
825
826 tcIfaceExpr (IfaceFCall cc ty) = do
827     ty' <- tcIfaceType ty
828     u <- newUnique
829     return (Var (mkFCallId u cc ty'))
830
831 tcIfaceExpr (IfaceTuple boxity args)  = do
832     args' <- mapM tcIfaceExpr args
833     -- Put the missing type arguments back in
834     let con_args = map (Type . exprType) args' ++ args'
835     return (mkApps (Var con_id) con_args)
836   where
837     arity = length args
838     con_id = dataConWorkId (tupleCon boxity arity)
839     
840
841 tcIfaceExpr (IfaceLam bndr body)
842   = bindIfaceBndr bndr $ \bndr' ->
843     Lam bndr' <$> tcIfaceExpr body
844
845 tcIfaceExpr (IfaceApp fun arg)
846   = App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
847
848 tcIfaceExpr (IfaceCase scrut case_bndr ty alts)  = do
849     scrut' <- tcIfaceExpr scrut
850     case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
851     let
852         scrut_ty   = exprType scrut'
853         case_bndr' = mkLocalId case_bndr_name scrut_ty
854         tc_app     = splitTyConApp scrut_ty
855                 -- NB: Won't always succeed (polymoprhic case)
856                 --     but won't be demanded in those cases
857                 -- NB: not tcSplitTyConApp; we are looking at Core here
858                 --     look through non-rec newtypes to find the tycon that
859                 --     corresponds to the datacon in this case alternative
860
861     extendIfaceIdEnv [case_bndr'] $ do
862      alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
863      ty' <- tcIfaceType ty
864      return (Case scrut' case_bndr' ty' alts')
865
866 tcIfaceExpr (IfaceLet (IfaceNonRec bndr rhs) body) = do
867     rhs' <- tcIfaceExpr rhs
868     id   <- tcIfaceLetBndr bndr
869     body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
870     return (Let (NonRec id rhs') body')
871
872 tcIfaceExpr (IfaceLet (IfaceRec pairs) body) = do
873     ids <- mapM tcIfaceLetBndr bndrs
874     extendIfaceIdEnv ids $ do
875      rhss' <- mapM tcIfaceExpr rhss
876      body' <- tcIfaceExpr body
877      return (Let (Rec (ids `zip` rhss')) body')
878   where
879     (bndrs, rhss) = unzip pairs
880
881 tcIfaceExpr (IfaceCast expr co) = do
882     expr' <- tcIfaceExpr expr
883     co' <- tcIfaceType co
884     return (Cast expr' co')
885
886 tcIfaceExpr (IfaceNote note expr) = do
887     expr' <- tcIfaceExpr expr
888     case note of
889         IfaceSCC cc       -> return (Note (SCC cc)   expr')
890         IfaceCoreNote n   -> return (Note (CoreNote n) expr')
891
892 -------------------------
893 tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
894            -> (IfaceConAlt, [FastString], IfaceExpr)
895            -> IfL (AltCon, [TyVar], CoreExpr)
896 tcIfaceAlt _ _ (IfaceDefault, names, rhs)
897   = ASSERT( null names ) do
898     rhs' <- tcIfaceExpr rhs
899     return (DEFAULT, [], rhs')
900   
901 tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
902   = ASSERT( null names ) do
903     rhs' <- tcIfaceExpr rhs
904     return (LitAlt lit, [], rhs')
905
906 -- A case alternative is made quite a bit more complicated
907 -- by the fact that we omit type annotations because we can
908 -- work them out.  True enough, but its not that easy!
909 tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
910   = do  { con <- tcIfaceDataCon data_occ
911         ; when (debugIsOn && not (con `elem` tyConDataCons tycon))
912                (failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
913         ; tcIfaceDataAlt con inst_tys arg_strs rhs }
914                   
915 tcIfaceAlt _ (tycon, inst_tys) (IfaceTupleAlt _boxity, arg_occs, rhs)
916   = ASSERT( isTupleTyCon tycon )
917     do  { let [data_con] = tyConDataCons tycon
918         ; tcIfaceDataAlt data_con inst_tys arg_occs rhs }
919
920 tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
921                -> IfL (AltCon, [TyVar], CoreExpr)
922 tcIfaceDataAlt con inst_tys arg_strs rhs
923   = do  { us <- newUniqueSupply
924         ; let uniqs = uniqsFromSupply us
925         ; let (ex_tvs, co_tvs, arg_ids)
926                       = dataConRepFSInstPat arg_strs uniqs con inst_tys
927               all_tvs = ex_tvs ++ co_tvs
928
929         ; rhs' <- extendIfaceTyVarEnv all_tvs   $
930                   extendIfaceIdEnv arg_ids      $
931                   tcIfaceExpr rhs
932         ; return (DataAlt con, all_tvs ++ arg_ids, rhs') }
933 \end{code}
934
935
936 \begin{code}
937 tcExtCoreBindings :: [IfaceBinding] -> IfL [CoreBind]   -- Used for external core
938 tcExtCoreBindings []     = return []
939 tcExtCoreBindings (b:bs) = do_one b (tcExtCoreBindings bs)
940
941 do_one :: IfaceBinding -> IfL [CoreBind] -> IfL [CoreBind]
942 do_one (IfaceNonRec bndr rhs) thing_inside
943   = do  { rhs' <- tcIfaceExpr rhs
944         ; bndr' <- newExtCoreBndr bndr
945         ; extendIfaceIdEnv [bndr'] $ do 
946         { core_binds <- thing_inside
947         ; return (NonRec bndr' rhs' : core_binds) }}
948
949 do_one (IfaceRec pairs) thing_inside
950   = do  { bndrs' <- mapM newExtCoreBndr bndrs
951         ; extendIfaceIdEnv bndrs' $ do
952         { rhss' <- mapM tcIfaceExpr rhss
953         ; core_binds <- thing_inside
954         ; return (Rec (bndrs' `zip` rhss') : core_binds) }}
955   where
956     (bndrs,rhss) = unzip pairs
957 \end{code}
958
959
960 %************************************************************************
961 %*                                                                      *
962                 IdInfo
963 %*                                                                      *
964 %************************************************************************
965
966 \begin{code}
967 tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
968 tcIdDetails _  IfVanillaId = return VanillaId
969 tcIdDetails ty IfDFunId
970   = return (DFunId (isNewTyCon (classTyCon cls)))
971   where
972     (_, cls, _) = tcSplitDFunTy ty
973
974 tcIdDetails _ (IfRecSelId tc naughty)
975   = do { tc' <- tcIfaceTyCon tc
976        ; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
977
978 tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
979 tcIdInfo ignore_prags name ty info 
980   | ignore_prags = return vanillaIdInfo
981   | otherwise    = case info of
982                         NoInfo       -> return vanillaIdInfo
983                         HasInfo info -> foldlM tcPrag init_info info
984   where
985     -- Set the CgInfo to something sensible but uninformative before
986     -- we start; default assumption is that it has CAFs
987     init_info = vanillaIdInfo
988
989     tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
990     tcPrag info HsNoCafRefs        = return (info `setCafInfo`   NoCafRefs)
991     tcPrag info (HsArity arity)    = return (info `setArityInfo` arity)
992     tcPrag info (HsStrictness str) = return (info `setAllStrictnessInfo` Just str)
993     tcPrag info (HsInline prag)    = return (info `setInlinePragInfo` prag)
994
995         -- The next two are lazy, so they don't transitively suck stuff in
996     tcPrag info (HsUnfold if_unf)  = do { unf <- tcUnfolding name ty info if_unf
997                                         ; return (info `setUnfoldingInfoLazily` unf) }
998 \end{code}
999
1000 \begin{code}
1001 tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
1002 tcUnfolding name _ _ (IfCoreUnfold if_expr)
1003   = do  { mb_expr <- tcPragExpr name if_expr
1004         ; return (case mb_expr of
1005                     Nothing -> NoUnfolding
1006                     Just expr -> mkTopUnfolding expr) }
1007
1008 tcUnfolding name _ _ (IfInlineRule arity sat if_expr)
1009   = do  { mb_expr <- tcPragExpr name if_expr
1010         ; return (case mb_expr of
1011                     Nothing   -> NoUnfolding
1012                     Just expr -> mkInlineRule inl_info expr arity) }
1013   where
1014     inl_info | sat       = InlSat
1015              | otherwise = InlUnSat
1016
1017 tcUnfolding name ty info (IfWrapper arity wkr)
1018   = do  { mb_wkr_id <- forkM_maybe doc (tcIfaceExtId wkr)
1019         ; us <- newUniqueSupply
1020         ; return (case mb_wkr_id of
1021                      Nothing     -> noUnfolding
1022                      Just wkr_id -> make_inline_rule wkr_id us) }
1023   where
1024     doc = text "Worker for" <+> ppr name
1025
1026     make_inline_rule wkr_id us 
1027         = mkWwInlineRule wkr_id
1028                          (initUs_ us (mkWrapper ty strict_sig) wkr_id) 
1029                          arity
1030
1031         -- We are relying here on strictness info always appearing 
1032         -- before worker info,  fingers crossed ....
1033     strict_sig = case newStrictnessInfo info of
1034                    Just sig -> sig
1035                    Nothing  -> pprPanic "Worker info but no strictness for" (ppr wkr)
1036
1037 tcUnfolding name dfun_ty _ (IfDFunUnfold ops)
1038   = do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
1039        ; return (case mb_ops1 of
1040                     Nothing   -> noUnfolding
1041                     Just ops1 -> DFunUnfolding data_con ops1) }
1042   where
1043     doc = text "Class ops for dfun" <+> ppr name
1044     (_, cls, _) = tcSplitDFunTy dfun_ty
1045     data_con = classDataCon cls
1046 \end{code}
1047
1048 For unfoldings we try to do the job lazily, so that we never type check
1049 an unfolding that isn't going to be looked at.
1050
1051 \begin{code}
1052 tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
1053 tcPragExpr name expr
1054   = forkM_maybe doc $ do
1055     core_expr' <- tcIfaceExpr expr
1056
1057                 -- Check for type consistency in the unfolding
1058     ifOptM Opt_DoCoreLinting $ do
1059         in_scope <- get_in_scope_ids
1060         case lintUnfolding noSrcLoc in_scope core_expr' of
1061           Nothing       -> return ()
1062           Just fail_msg -> pprPanic "Iface Lint failure" (hang doc 2 fail_msg)
1063
1064     return core_expr'
1065   where
1066     doc = text "Unfolding of" <+> ppr name
1067     get_in_scope_ids    -- Urgh; but just for linting
1068         = setLclEnv () $ 
1069           do    { env <- getGblEnv 
1070                 ; case if_rec_types env of {
1071                           Nothing -> return [] ;
1072                           Just (_, get_env) -> do
1073                 { type_env <- get_env
1074                 ; return (typeEnvIds type_env) }}}
1075 \end{code}
1076
1077
1078
1079 %************************************************************************
1080 %*                                                                      *
1081                 Getting from Names to TyThings
1082 %*                                                                      *
1083 %************************************************************************
1084
1085 \begin{code}
1086 tcIfaceGlobal :: Name -> IfL TyThing
1087 tcIfaceGlobal name
1088   | Just thing <- wiredInNameTyThing_maybe name
1089         -- Wired-in things include TyCons, DataCons, and Ids
1090   = do { ifCheckWiredInThing thing; return thing }
1091   | otherwise
1092   = do  { env <- getGblEnv
1093         ; case if_rec_types env of {    -- Note [Tying the knot]
1094             Just (mod, get_type_env) 
1095                 | nameIsLocalOrFrom mod name
1096                 -> do           -- It's defined in the module being compiled
1097                 { type_env <- setLclEnv () get_type_env         -- yuk
1098                 ; case lookupNameEnv type_env name of
1099                         Just thing -> return thing
1100                         Nothing   -> pprPanic "tcIfaceGlobal (local): not found:"  
1101                                                 (ppr name $$ ppr type_env) }
1102
1103           ; _ -> do
1104
1105         { hsc_env <- getTopEnv
1106         ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
1107         ; case mb_thing of {
1108             Just thing -> return thing ;
1109             Nothing    -> do
1110
1111         { mb_thing <- importDecl name   -- It's imported; go get it
1112         ; case mb_thing of
1113             Failed err      -> failIfM err
1114             Succeeded thing -> return thing
1115     }}}}}
1116
1117 -- Note [Tying the knot]
1118 -- ~~~~~~~~~~~~~~~~~~~~~
1119 -- The if_rec_types field is used in two situations:
1120 --
1121 -- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
1122 --    Then we look up M.T in M's type environment, which is splatted into if_rec_types
1123 --    after we've built M's type envt.
1124 --
1125 -- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
1126 --    is up to date.  So we call typecheckIface on M.hi.  This splats M.T into 
1127 --    if_rec_types so that the (lazily typechecked) decls see all the other decls
1128 --
1129 -- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
1130 -- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
1131 -- emasculated form (e.g. lacking data constructors).
1132
1133 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
1134 tcIfaceTyCon IfaceIntTc         = tcWiredInTyCon intTyCon
1135 tcIfaceTyCon IfaceBoolTc        = tcWiredInTyCon boolTyCon
1136 tcIfaceTyCon IfaceCharTc        = tcWiredInTyCon charTyCon
1137 tcIfaceTyCon IfaceListTc        = tcWiredInTyCon listTyCon
1138 tcIfaceTyCon IfacePArrTc        = tcWiredInTyCon parrTyCon
1139 tcIfaceTyCon (IfaceTupTc bx ar) = tcWiredInTyCon (tupleTyCon bx ar)
1140 tcIfaceTyCon (IfaceAnyTc kind)  = do { tc_kind <- tcIfaceType kind
1141                                      ; tcWiredInTyCon (anyTyConOfKind tc_kind) }
1142 tcIfaceTyCon (IfaceTc name)     = do { thing <- tcIfaceGlobal name 
1143                                      ; return (check_tc (tyThingTyCon thing)) }
1144   where
1145     check_tc tc
1146      | debugIsOn = case toIfaceTyCon tc of
1147                    IfaceTc _ -> tc
1148                    _         -> pprTrace "check_tc" (ppr tc) tc
1149      | otherwise = tc
1150 -- we should be okay just returning Kind constructors without extra loading
1151 tcIfaceTyCon IfaceLiftedTypeKindTc   = return liftedTypeKindTyCon
1152 tcIfaceTyCon IfaceOpenTypeKindTc     = return openTypeKindTyCon
1153 tcIfaceTyCon IfaceUnliftedTypeKindTc = return unliftedTypeKindTyCon
1154 tcIfaceTyCon IfaceArgTypeKindTc      = return argTypeKindTyCon
1155 tcIfaceTyCon IfaceUbxTupleKindTc     = return ubxTupleKindTyCon
1156
1157 -- Even though we are in an interface file, we want to make
1158 -- sure the instances and RULES of this tycon are loaded 
1159 -- Imagine: f :: Double -> Double
1160 tcWiredInTyCon :: TyCon -> IfL TyCon
1161 tcWiredInTyCon tc = do { ifCheckWiredInThing (ATyCon tc)
1162                        ; return tc }
1163
1164 tcIfaceClass :: Name -> IfL Class
1165 tcIfaceClass name = do { thing <- tcIfaceGlobal name
1166                        ; return (tyThingClass thing) }
1167
1168 tcIfaceDataCon :: Name -> IfL DataCon
1169 tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
1170                          ; case thing of
1171                                 ADataCon dc -> return dc
1172                                 _       -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
1173
1174 tcIfaceExtId :: Name -> IfL Id
1175 tcIfaceExtId name = do { thing <- tcIfaceGlobal name
1176                        ; case thing of
1177                           AnId id -> return id
1178                           _       -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
1179 \end{code}
1180
1181 %************************************************************************
1182 %*                                                                      *
1183                 Bindings
1184 %*                                                                      *
1185 %************************************************************************
1186
1187 \begin{code}
1188 bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
1189 bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
1190   = do  { name <- newIfaceName (mkVarOccFS fs)
1191         ; ty' <- tcIfaceType ty
1192         ; let id = mkLocalId name ty'
1193         ; extendIfaceIdEnv [id] (thing_inside id) }
1194 bindIfaceBndr (IfaceTvBndr bndr) thing_inside
1195   = bindIfaceTyVar bndr thing_inside
1196     
1197 bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
1198 bindIfaceBndrs []     thing_inside = thing_inside []
1199 bindIfaceBndrs (b:bs) thing_inside
1200   = bindIfaceBndr b     $ \ b' ->
1201     bindIfaceBndrs bs   $ \ bs' ->
1202     thing_inside (b':bs')
1203
1204
1205 -----------------------
1206 tcIfaceLetBndr :: IfaceLetBndr -> IfL Id
1207 tcIfaceLetBndr (IfLetBndr fs ty info)
1208   = do  { name <- newIfaceName (mkVarOccFS fs)
1209         ; ty' <- tcIfaceType ty
1210         ; case info of
1211                 NoInfo    -> return (mkLocalId name ty')
1212                 HasInfo i -> return (mkLocalIdWithInfo name ty' (tc_info i)) } 
1213   where
1214         -- Similar to tcIdInfo, but much simpler
1215     tc_info [] = vanillaIdInfo
1216     tc_info (HsInline p     : i) = tc_info i `setInlinePragInfo` p 
1217     tc_info (HsArity a      : i) = tc_info i `setArityInfo` a 
1218     tc_info (HsStrictness s : i) = tc_info i `setAllStrictnessInfo` Just s 
1219     tc_info (other          : i) = pprTrace "tcIfaceLetBndr: discarding unexpected IdInfo" 
1220                                             (ppr other) (tc_info i)
1221
1222 -----------------------
1223 newExtCoreBndr :: IfaceLetBndr -> IfL Id
1224 newExtCoreBndr (IfLetBndr var ty _)    -- Ignoring IdInfo for now
1225   = do  { mod <- getIfModule
1226         ; name <- newGlobalBinder mod (mkVarOccFS var) noSrcSpan
1227         ; ty' <- tcIfaceType ty
1228         ; return (mkLocalId name ty') }
1229
1230 -----------------------
1231 bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
1232 bindIfaceTyVar (occ,kind) thing_inside
1233   = do  { name <- newIfaceName (mkTyVarOccFS occ)
1234         ; tyvar <- mk_iface_tyvar name kind
1235         ; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
1236
1237 bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1238 bindIfaceTyVars bndrs thing_inside
1239   = do  { names <- newIfaceNames (map mkTyVarOccFS occs)
1240         ; tyvars <- zipWithM mk_iface_tyvar names kinds
1241         ; extendIfaceTyVarEnv tyvars (thing_inside tyvars) }
1242   where
1243     (occs,kinds) = unzip bndrs
1244
1245 mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
1246 mk_iface_tyvar name ifKind
1247    = do { kind <- tcIfaceType ifKind
1248         ; if isCoercionKind kind then 
1249                 return (Var.mkCoVar name kind)
1250           else
1251                 return (Var.mkTyVar name kind) }
1252
1253 bindIfaceTyVars_AT :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
1254 -- Used for type variable in nested associated data/type declarations
1255 -- where some of the type variables are already in scope
1256 --    class C a where { data T a b }
1257 -- Here 'a' is in scope when we look at the 'data T'
1258 bindIfaceTyVars_AT [] thing_inside
1259   = thing_inside []
1260 bindIfaceTyVars_AT (b@(tv_occ,_) : bs) thing_inside 
1261   = bindIfaceTyVars_AT bs $ \ bs' ->
1262     do { mb_tv <- lookupIfaceTyVar tv_occ
1263        ; case mb_tv of
1264            Just b' -> thing_inside (b':bs')
1265            Nothing -> bindIfaceTyVar b $ \ b' -> 
1266                       thing_inside (b':bs') }
1267 \end{code} 
1268