f83b337f3e35218aa679f4ab28c5295705c5e97b
[ghc-hetmet.git] / ghc / compiler / typecheck / TcIfaceSig.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcIfaceSig]{Type checking of type signatures in interface files}
5
6 \begin{code}
7 module TcIfaceSig ( tcInterfaceSigs,
8                     tcDelay,
9                     tcVar,
10                     tcCoreExpr,
11                     tcCoreLamBndrs,
12                     tcCoreBinds ) where
13
14 #include "HsVersions.h"
15
16 import HsSyn            ( TyClDecl(..), HsTupCon(..) )
17 import TcHsSyn          ( TypecheckedCoreBind )
18 import TcMonad
19 import TcMonoType       ( tcIfaceType )
20 import TcEnv            ( RecTcEnv, tcExtendTyVarEnv, 
21                           tcExtendGlobalValEnv, tcSetEnv, tcEnvIds,
22                           tcLookupGlobal_maybe, tcLookupRecId_maybe
23                         )
24
25 import RnHsSyn          ( RenamedTyClDecl )
26 import HsCore
27 import Literal          ( Literal(..) )
28 import CoreSyn
29 import CoreUtils        ( exprType )
30 import CoreUnfold
31 import CoreLint         ( lintUnfolding )
32 import WorkWrap         ( mkWrapper )
33
34 import Id               ( Id, mkVanillaGlobal, mkLocalId, idName, isDataConWrapId_maybe )
35 import Module           ( Module )
36 import MkId             ( mkFCallId )
37 import IdInfo
38 import TyCon            ( tyConDataCons, tyConTyVars )
39 import DataCon          ( DataCon, dataConWorkId, dataConExistentialTyVars, dataConArgTys )
40 import Type             ( Type, mkTyVarTys, splitTyConApp )
41 import TysWiredIn       ( tupleCon )
42 import Var              ( mkTyVar, tyVarKind )
43 import Name             ( Name, nameIsLocalOrFrom )
44 import ErrUtils         ( pprBagOfErrors )
45 import Outputable       
46 import Util             ( zipWithEqual, dropList, equalLength )
47 import HscTypes         ( TyThing(..) )
48 \end{code}
49
50 Ultimately, type signatures in interfaces will have pragmatic
51 information attached, so it is a good idea to have separate code to
52 check them.
53
54 As always, we do not have to worry about user-pragmas in interface
55 signatures.
56
57 \begin{code}
58 tcInterfaceSigs :: RecTcEnv             -- Envt to use when checking unfoldings
59                 -> Module               -- This module
60                 -> [RenamedTyClDecl]    -- Ignore non-sig-decls in these decls
61                 -> TcM [Id]
62                 
63
64 tcInterfaceSigs unf_env mod decls
65   = listTc [ do_one name ty id_infos src_loc
66            | IfaceSig {tcdName = name, tcdType = ty, tcdIdInfo = id_infos, tcdLoc =src_loc} <- decls]
67   where
68     in_scope_vars = filter (nameIsLocalOrFrom mod . idName) (tcEnvIds unf_env)
69                 -- Oops: using isLocalId instead can give a black hole
70                 -- because it looks at the idinfo
71
72         -- When we have hi-boot files, an unfolding might refer to
73         -- something defined in this module, so we must build a
74         -- suitable in-scope set.  This thunk will only be poked
75         -- if -dcore-lint is on.
76
77     do_one name ty id_infos src_loc
78       = tcAddSrcLoc src_loc                             $       
79         tcAddErrCtxt (ifaceSigCtxt name)                $
80         tcIfaceType ty                                  `thenTc` \ sigma_ty ->
81         tcIdInfo unf_env in_scope_vars name 
82                  sigma_ty id_infos                      `thenTc` \ id_info ->
83         returnTc (mkVanillaGlobal name sigma_ty id_info)
84 \end{code}
85
86 \begin{code}
87 tcIdInfo unf_env in_scope_vars name ty info_ins
88   = foldlTc tcPrag init_info info_ins 
89   where
90     -- set the CgInfo to something sensible but uninformative before
91     -- we start, because the default CgInfo is a panic.
92     init_info = vanillaIdInfo `setCgInfo` vanillaCgInfo
93
94     tcPrag info (HsNoCafRefs)   = returnTc (info `setCafInfo`    NoCafRefs)
95
96     tcPrag info (HsArity arity) = 
97         returnTc (info `setArityInfo` arity)
98
99     tcPrag info (HsUnfold inline_prag expr)
100         = tcPragExpr unf_env name in_scope_vars expr    `thenNF_Tc` \ maybe_expr' ->
101           let
102                 -- maybe_expr doesn't get looked at if the unfolding
103                 -- is never inspected; so the typecheck doesn't even happen
104                 unfold_info = case maybe_expr' of
105                                 Nothing    -> noUnfolding
106                                 Just expr' -> mkTopUnfolding expr' 
107                 info1 = info `setUnfoldingInfo` unfold_info
108                 info2 = info1 `setInlinePragInfo` inline_prag
109           in
110           returnTc info2
111
112     tcPrag info (HsStrictness strict_info)
113         = returnTc (info `setAllStrictnessInfo` Just strict_info)
114
115     tcPrag info (HsWorker nm arity)
116         = tcWorkerInfo unf_env ty info nm arity
117 \end{code}
118
119 \begin{code}
120 tcWorkerInfo unf_env ty info worker_name arity
121   = uniqSMToTcM (mkWrapper ty strict_sig) `thenNF_Tc` \ wrap_fn ->
122     let
123         -- Watch out! We can't pull on unf_env too eagerly!
124         info' = case tcLookupRecId_maybe unf_env worker_name of
125                   Just worker_id -> 
126                     info `setUnfoldingInfo`  mkTopUnfolding (wrap_fn worker_id)
127                          `setWorkerInfo`     HasWorker worker_id arity
128
129                   Nothing -> pprTrace "tcWorkerInfo failed:" 
130                                 (ppr worker_name) info
131     in
132     returnTc info'
133   where
134         -- We are relying here on strictness info always appearing 
135         -- before worker info,  fingers crossed ....
136       strict_sig = case newStrictnessInfo info of
137                         Just sig -> sig
138                         Nothing  -> pprPanic "Worker info but no strictness for" (ppr worker_name)
139 \end{code}
140
141 For unfoldings we try to do the job lazily, so that we never type check
142 an unfolding that isn't going to be looked at.
143
144 \begin{code}
145 tcPragExpr unf_env name in_scope_vars expr
146   = tcDelay unf_env doc Nothing $
147         tcCoreExpr expr         `thenTc` \ core_expr' ->
148
149                 -- Check for type consistency in the unfolding
150         tcGetSrcLoc             `thenNF_Tc` \ src_loc -> 
151         getDOptsTc              `thenNF_Tc` \ dflags ->
152         case lintUnfolding dflags src_loc in_scope_vars core_expr' of
153           (Nothing,_)       -> returnTc (Just core_expr')  -- ignore warnings
154           (Just fail_msg,_) -> failWithTc ((doc <+> text "failed Lint") $$ fail_msg)
155   where
156     doc = text "unfolding of" <+> ppr name
157
158 tcDelay :: RecTcEnv -> SDoc -> a -> TcM a -> NF_TcM a
159 tcDelay unf_env doc bad_ans thing_inside
160   = forkNF_Tc (
161         recoverNF_Tc bad_value (
162                 tcSetEnv unf_env thing_inside
163     ))                  
164   where
165         -- The trace tells what wasn't available, for the benefit of
166         -- compiler hackers who want to improve it!
167     bad_value = getErrsTc               `thenNF_Tc` \ (warns,errs) ->
168                 returnNF_Tc (pprTrace "Failed:" 
169                                          (hang doc 4 (pprBagOfErrors errs))
170                                          bad_ans)
171 \end{code}
172
173
174 Variables in unfoldings
175 ~~~~~~~~~~~~~~~~~~~~~~~
176 ****** Inside here we use only the Global environment, even for locally bound variables.
177 ****** Why? Because we know all the types and want to bind them to real Ids.
178
179 \begin{code}
180 tcVar :: Name -> TcM Id
181 tcVar name
182   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_id ->
183     case maybe_id of {
184         Just (AnId id)  -> returnTc id ;
185         Nothing         -> failWithTc (noDecl name)
186     }
187
188 noDecl name = hsep [ptext SLIT("Warning: no binding for"), ppr name]
189 \end{code}
190
191 UfCore expressions.
192
193 \begin{code}
194 tcCoreExpr :: UfExpr Name -> TcM CoreExpr
195
196 tcCoreExpr (UfType ty)
197   = tcIfaceType ty              `thenTc` \ ty' ->
198         -- It might not be of kind type
199     returnTc (Type ty')
200
201 tcCoreExpr (UfVar name)
202   = tcVar name  `thenTc` \ id ->
203     returnTc (Var id)
204
205 tcCoreExpr (UfLit lit)
206   = returnTc (Lit lit)
207
208 -- The dreaded lit-lits are also similar, except here the type
209 -- is read in explicitly rather than being implicit
210 tcCoreExpr (UfLitLit lit ty)
211   = tcIfaceType ty              `thenTc` \ ty' ->
212     returnTc (Lit (MachLitLit lit ty'))
213
214 tcCoreExpr (UfFCall cc ty)
215   = tcIfaceType ty      `thenTc` \ ty' ->
216     tcGetUnique         `thenNF_Tc` \ u ->
217     returnTc (Var (mkFCallId u cc ty'))
218
219 tcCoreExpr (UfTuple (HsTupCon _ boxity arity) args) 
220   = mapTc tcCoreExpr args       `thenTc` \ args' ->
221     let
222         -- Put the missing type arguments back in
223         con_args = map (Type . exprType) args' ++ args'
224     in
225     returnTc (mkApps (Var con_id) con_args)
226   where
227     con_id = dataConWorkId (tupleCon boxity arity)
228     
229
230 tcCoreExpr (UfLam bndr body)
231   = tcCoreLamBndr bndr          $ \ bndr' ->
232     tcCoreExpr body             `thenTc` \ body' ->
233     returnTc (Lam bndr' body')
234
235 tcCoreExpr (UfApp fun arg)
236   = tcCoreExpr fun              `thenTc` \ fun' ->
237     tcCoreExpr arg              `thenTc` \ arg' ->
238     returnTc (App fun' arg')
239
240 tcCoreExpr (UfCase scrut case_bndr alts) 
241   = tcCoreExpr scrut                                    `thenTc` \ scrut' ->
242     let
243         scrut_ty = exprType scrut'
244         case_bndr' = mkLocalId case_bndr scrut_ty
245     in
246     tcExtendGlobalValEnv [case_bndr']   $
247     mapTc (tcCoreAlt scrut_ty) alts     `thenTc` \ alts' ->
248     returnTc (Case scrut' case_bndr' alts')
249
250 tcCoreExpr (UfLet (UfNonRec bndr rhs) body)
251   = tcCoreExpr rhs              `thenTc` \ rhs' ->
252     tcCoreValBndr bndr          $ \ bndr' ->
253     tcCoreExpr body             `thenTc` \ body' ->
254     returnTc (Let (NonRec bndr' rhs') body')
255
256 tcCoreExpr (UfLet (UfRec pairs) body)
257   = tcCoreValBndrs bndrs        $ \ bndrs' ->
258     mapTc tcCoreExpr rhss       `thenTc` \ rhss' ->
259     tcCoreExpr body             `thenTc` \ body' ->
260     returnTc (Let (Rec (bndrs' `zip` rhss')) body')
261   where
262     (bndrs, rhss) = unzip pairs
263
264 tcCoreExpr (UfNote note expr) 
265   = tcCoreExpr expr             `thenTc` \ expr' ->
266     case note of
267         UfCoerce to_ty -> tcIfaceType to_ty     `thenTc` \ to_ty' ->
268                           returnTc (Note (Coerce to_ty'
269                                                  (exprType expr')) expr')
270         UfInlineCall   -> returnTc (Note InlineCall expr')
271         UfInlineMe     -> returnTc (Note InlineMe   expr')
272         UfSCC cc       -> returnTc (Note (SCC cc)   expr')
273 \end{code}
274
275 \begin{code}
276 tcCoreLamBndr (UfValBinder name ty) thing_inside
277   = tcIfaceType ty              `thenTc` \ ty' ->
278     let
279         id = mkLocalId name ty'
280     in
281     tcExtendGlobalValEnv [id] $
282     thing_inside id
283     
284 tcCoreLamBndr (UfTyBinder name kind) thing_inside
285   = let
286         tyvar = mkTyVar name kind
287     in
288     tcExtendTyVarEnv [tyvar] (thing_inside tyvar)
289     
290 tcCoreLamBndrs []     thing_inside = thing_inside []
291 tcCoreLamBndrs (b:bs) thing_inside
292   = tcCoreLamBndr b     $ \ b' ->
293     tcCoreLamBndrs bs   $ \ bs' ->
294     thing_inside (b':bs')
295
296 tcCoreValBndr (UfValBinder name ty) thing_inside
297   = tcIfaceType ty                      `thenTc` \ ty' ->
298     let
299         id = mkLocalId name ty'
300     in
301     tcExtendGlobalValEnv [id] $
302     thing_inside id
303     
304 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
305   = mapTc tcIfaceType tys               `thenTc` \ tys' ->
306     let
307         ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys'
308     in
309     tcExtendGlobalValEnv ids $
310     thing_inside ids
311   where
312     names = [name | UfValBinder name _  <- bndrs]
313     tys   = [ty   | UfValBinder _    ty <- bndrs]
314 \end{code}    
315
316 \begin{code}
317 tcCoreAlt scrut_ty (UfDefault, names, rhs)
318   = ASSERT( null names )
319     tcCoreExpr rhs              `thenTc` \ rhs' ->
320     returnTc (DEFAULT, [], rhs')
321   
322 tcCoreAlt scrut_ty (UfLitAlt lit, names, rhs)
323   = ASSERT( null names )
324     tcCoreExpr rhs              `thenTc` \ rhs' ->
325     returnTc (LitAlt lit, [], rhs')
326
327 tcCoreAlt scrut_ty (UfLitLitAlt str ty, names, rhs)
328   = ASSERT( null names )
329     tcCoreExpr rhs              `thenTc` \ rhs' ->
330     tcIfaceType ty              `thenTc` \ ty' ->
331     returnTc (LitAlt (MachLitLit str ty'), [], rhs')
332
333 -- A case alternative is made quite a bit more complicated
334 -- by the fact that we omit type annotations because we can
335 -- work them out.  True enough, but its not that easy!
336 tcCoreAlt scrut_ty alt@(con, names, rhs)
337   = tcConAlt con        `thenTc` \ con ->
338     let
339         ex_tyvars         = dataConExistentialTyVars con
340         (tycon, inst_tys) = splitTyConApp scrut_ty      -- NB: not tcSplitTyConApp
341                                                         -- We are looking at Core here
342         main_tyvars       = tyConTyVars tycon
343         ex_tyvars'        = [mkTyVar name (tyVarKind tv) | (name,tv) <- names `zip` ex_tyvars] 
344         ex_tys'           = mkTyVarTys ex_tyvars'
345         arg_tys           = dataConArgTys con (inst_tys ++ ex_tys')
346         id_names          = dropList ex_tyvars names
347         arg_ids
348 #ifdef DEBUG
349                 | not (equalLength id_names arg_tys)
350                 = pprPanic "tcCoreAlts" (ppr (con, names, rhs) $$
351                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
352                                          ppr arg_tys)
353                 | otherwise
354 #endif
355                 = zipWithEqual "tcCoreAlts" mkLocalId id_names arg_tys
356     in
357     ASSERT( con `elem` tyConDataCons tycon && equalLength inst_tys main_tyvars )
358     tcExtendTyVarEnv ex_tyvars'                 $
359     tcExtendGlobalValEnv arg_ids                $
360     tcCoreExpr rhs                                      `thenTc` \ rhs' ->
361     returnTc (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
362
363
364 tcConAlt :: UfConAlt Name -> TcM DataCon
365 tcConAlt (UfTupleAlt (HsTupCon _ boxity arity))
366   = returnTc (tupleCon boxity arity)
367
368 tcConAlt (UfDataAlt con_name)
369   = tcVar con_name      `thenTc` \ con_id ->
370     returnTc (case isDataConWrapId_maybe con_id of
371                     Just con -> con
372                     Nothing  -> pprPanic "tcCoreAlt" (ppr con_id))
373 \end{code}
374
375 %************************************************************************
376 %*                                                                      *
377 \subsection{Core decls}
378 %*                                                                      *
379 %************************************************************************
380
381
382 \begin{code}
383 tcCoreBinds :: [RenamedTyClDecl] -> TcM [TypecheckedCoreBind]
384 -- We don't assume the bindings are in dependency order
385 -- So first build the environment, then check the RHSs
386 tcCoreBinds ls = mapTc tcCoreBinder ls          `thenTc` \ bndrs ->
387                  tcExtendGlobalValEnv bndrs     $
388                  mapTc tcCoreBind ls
389
390 tcCoreBinder (CoreDecl { tcdName = nm, tcdType = ty })
391  = tcIfaceType ty   `thenTc` \ ty' ->
392    returnTc (mkLocalId nm ty')
393
394 tcCoreBind (CoreDecl { tcdName = nm, tcdRhs = rhs })
395  = tcVar nm             `thenTc` \ id ->
396    tcCoreExpr rhs       `thenTc` \ rhs' ->
397    returnTc (id, rhs')
398 \end{code}
399
400
401 \begin{code}
402 ifaceSigCtxt sig_name
403   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
404 \end{code}
405