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