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