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