[project @ 1999-06-22 07:59:54 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, tcVar, tcCoreExpr, tcCoreLamBndrs ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( HsDecl(..), IfaceSig(..) )
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                           tcLookupTyConByKey, tcLookupValueMaybe,
22                           explicitLookupValue, badCon, badPrimOp
23                         )
24 import TcType           ( TcKind, kindToTcKind )
25
26 import RnHsSyn          ( RenamedHsDecl )
27 import HsCore
28 import CallConv         ( cCallConv )
29 import Const            ( Con(..), Literal(..) )
30 import CoreSyn
31 import CoreUtils        ( coreExprType )
32 import CoreUnfold
33 import CoreLint         ( lintUnfolding )
34 import WwLib            ( mkWrapper )
35 import PrimOp           ( PrimOp(..) )
36
37 import Id               ( Id, mkId, mkVanillaId,
38                           isPrimitiveId_maybe, isDataConId_maybe
39                         )
40 import IdInfo
41 import DataCon          ( dataConSig, dataConArgTys )
42 import Type             ( mkSynTy, mkTyVarTys, splitAlgTyConApp )
43 import Var              ( IdOrTyVar, mkTyVar, tyVarKind )
44 import VarEnv
45 import Name             ( Name, NamedThing(..) )
46 import Unique           ( rationalTyConKey )
47 import TysWiredIn       ( integerTy, stringTy )
48 import Demand           ( wwLazy )
49 import ErrUtils         ( pprBagOfErrors )
50 import Maybes           ( maybeToBool, MaybeErr(..) )
51 import Outputable       
52 import Util             ( zipWithEqual )
53 \end{code}
54
55 Ultimately, type signatures in interfaces will have pragmatic
56 information attached, so it is a good idea to have separate code to
57 check them.
58
59 As always, we do not have to worry about user-pragmas in interface
60 signatures.
61
62 \begin{code}
63 tcInterfaceSigs :: ValueEnv             -- Envt to use when checking unfoldings
64                 -> [RenamedHsDecl]      -- Ignore non-sig-decls in these decls
65                 -> TcM s [Id]
66                 
67
68 tcInterfaceSigs unf_env (SigD (IfaceSig name ty id_infos src_loc) : rest)
69   = tcAddSrcLoc src_loc (
70     tcAddErrCtxt (ifaceSigCtxt name) (
71         tcHsType ty                                             `thenTc` \ sigma_ty ->
72         tcIdInfo unf_env name sigma_ty vanillaIdInfo id_infos   `thenTc` \ id_info ->
73         returnTc (mkId name sigma_ty id_info)
74     ))                                          `thenTc` \ sig_id ->
75     tcInterfaceSigs unf_env rest                `thenTc` \ sig_ids ->
76     returnTc (sig_id : sig_ids)
77
78 tcInterfaceSigs unf_env (other_decl : rest) = tcInterfaceSigs unf_env rest
79
80 tcInterfaceSigs unf_env [] = returnTc []
81 \end{code}
82
83 \begin{code}
84 tcIdInfo unf_env name ty info info_ins
85   = foldlTc tcPrag vanillaIdInfo info_ins
86   where
87     tcPrag info (HsArity arity) = returnTc (info `setArityInfo`  arity)
88     tcPrag info (HsUpdate upd)  = returnTc (info `setUpdateInfo` upd)
89     tcPrag info (HsNoCafRefs)   = returnTc (info `setCafInfo`    NoCafRefs)
90     tcPrag info (HsCprInfo cpr_info)     = returnTc (info `setCprInfo` cpr_info)
91
92     tcPrag info (HsUnfold inline_prag maybe_expr)
93         = (case maybe_expr of
94                 Just expr -> tcPragExpr unf_env name [] expr
95                 Nothing   -> returnNF_Tc Nothing
96           )                                     `thenNF_Tc` \ maybe_expr' ->
97           let
98                 -- maybe_expr doesn't get looked at if the unfolding
99                 -- is never inspected; so the typecheck doesn't even happen
100                 unfold_info = case maybe_expr' of
101                                 Nothing    -> noUnfolding
102                                 Just expr' -> mkUnfolding expr' 
103                 info1 = info `setUnfoldingInfo` unfold_info
104                 info2 = info1 `setInlinePragInfo` inline_prag
105           in
106           returnTc info2
107
108     tcPrag info (HsStrictness (HsStrictnessInfo (demands,bot_result)))
109         = returnTc (info `setStrictnessInfo` StrictnessInfo demands bot_result)
110
111     tcPrag info (HsWorker nm)
112         = tcWorkerInfo unf_env ty info nm
113 \end{code}
114
115 \begin{code}
116 tcWorkerInfo unf_env ty info worker_name
117   | arity == 0
118   = pprPanic "Worker with no arity info" (ppr worker_name)
119  
120   | otherwise
121   = uniqSMToTcM (mkWrapper ty arity demands cpr_info) `thenNF_Tc` \ wrap_fn ->
122     let
123         -- Watch out! We can't pull on unf_env too eagerly!
124         info' = case explicitLookupValue unf_env worker_name of
125                         Just worker_id -> info `setUnfoldingInfo`  mkUnfolding (wrap_fn worker_id)
126                                                `setWorkerInfo`     Just worker_id
127
128                         Nothing        -> pprTrace "tcWorkerInfo failed:" (ppr worker_name) info
129     in
130     returnTc info'
131   where
132         -- We are relying here on arity, cpr and strictness info always appearing 
133         -- before worker info,  fingers crossed ....
134       arity    = arityLowerBound (arityInfo info)
135       cpr_info = cprInfo info
136       demands  = case strictnessInfo info of
137                         StrictnessInfo d _ -> d
138                         _                  -> repeat wwLazy     -- Noncommittal
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 $
147         tcCoreExpr expr         `thenTc` \ core_expr' ->
148
149                 -- Check for type consistency in the unfolding
150         tcGetSrcLoc             `thenNF_Tc` \ src_loc -> 
151         case lintUnfolding src_loc in_scope_vars core_expr' of
152           Nothing       -> returnTc core_expr'
153           Just fail_msg -> failWithTc ((doc <+> text "failed Lint") $$ fail_msg)
154   where
155     doc = text "unfolding of" <+> ppr name
156
157 tcDelay :: ValueEnv -> SDoc -> TcM s a -> NF_TcM s (Maybe a)
158 tcDelay unf_env doc thing_inside
159   = forkNF_Tc (
160         recoverNF_Tc bad_value (
161                 tcSetValueEnv unf_env thing_inside      `thenTc` \ r ->
162                 returnTc (Just r)
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                                          Nothing)
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 s Id
181 tcVar name
182   = tcLookupValueMaybe name     `thenNF_Tc` \ maybe_id ->
183     case maybe_id of {
184         Just 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 s CoreExpr
195
196 tcCoreExpr (UfType ty)
197   = tcHsTypeKind 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 (UfCon con args) 
206   = tcUfCon con                 `thenTc` \ con' ->
207     mapTc tcCoreExpr args       `thenTc` \ args' ->
208     returnTc (Con con' args')
209
210 tcCoreExpr (UfTuple name args) 
211   = tcUfDataCon name            `thenTc` \ con ->
212     mapTc tcCoreExpr args       `thenTc` \ args' ->
213     let
214         -- Put the missing type arguments back in
215         con_args = map (Type . coreExprType) args' ++ args'
216     in
217     returnTc (Con con con_args)
218
219 tcCoreExpr (UfLam bndr body)
220   = tcCoreLamBndr bndr          $ \ bndr' ->
221     tcCoreExpr body             `thenTc` \ body' ->
222     returnTc (Lam bndr' body')
223
224 tcCoreExpr (UfApp fun arg)
225   = tcCoreExpr fun              `thenTc` \ fun' ->
226     tcCoreExpr arg              `thenTc` \ arg' ->
227     returnTc (App fun' arg')
228
229 tcCoreExpr (UfCase scrut case_bndr alts) 
230   = tcCoreExpr scrut                                    `thenTc` \ scrut' ->
231     let
232         scrut_ty = coreExprType scrut'
233         case_bndr' = mkVanillaId case_bndr scrut_ty
234     in
235     tcExtendGlobalValEnv [case_bndr']   $
236     mapTc (tcCoreAlt scrut_ty) alts     `thenTc` \ alts' ->
237     returnTc (Case scrut' case_bndr' alts')
238
239 tcCoreExpr (UfLet (UfNonRec bndr rhs) body)
240   = tcCoreExpr rhs              `thenTc` \ rhs' ->
241     tcCoreValBndr bndr          $ \ bndr' ->
242     tcCoreExpr body             `thenTc` \ body' ->
243     returnTc (Let (NonRec bndr' rhs') body')
244
245 tcCoreExpr (UfLet (UfRec pairs) body)
246   = tcCoreValBndrs bndrs        $ \ bndrs' ->
247     mapTc tcCoreExpr rhss       `thenTc` \ rhss' ->
248     tcCoreExpr body             `thenTc` \ body' ->
249     returnTc (Let (Rec (bndrs' `zip` rhss')) body')
250   where
251     (bndrs, rhss) = unzip pairs
252
253 tcCoreExpr (UfNote note expr) 
254   = tcCoreExpr expr             `thenTc` \ expr' ->
255     case note of
256         UfCoerce to_ty -> tcHsType to_ty        `thenTc` \ to_ty' ->
257                           returnTc (Note (Coerce to_ty' (coreExprType expr')) expr')
258         UfInlineCall   -> returnTc (Note InlineCall expr')
259         UfInlineMe     -> returnTc (Note InlineMe   expr')
260         UfSCC cc       -> returnTc (Note (SCC cc)   expr')
261
262 tcCoreNote (UfSCC cc)   = returnTc (SCC cc)
263 tcCoreNote UfInlineCall = returnTc InlineCall 
264
265
266 -- rationalTy isn't built in so, we have to construct it
267 -- (the "ty" part of the incoming literal is simply bottom)
268 tcUfCon (UfLitCon (NoRepRational lit _)) 
269   = tcLookupTyConByKey rationalTyConKey `thenNF_Tc` \ rational_tycon ->
270     let
271         rational_ty  = mkSynTy rational_tycon []
272     in
273     returnTc (Literal (NoRepRational lit rational_ty)) 
274
275 -- Similarly for integers and strings, except that they are wired in
276 tcUfCon (UfLitCon (NoRepInteger lit _)) 
277   = returnTc (Literal (NoRepInteger lit integerTy))
278 tcUfCon (UfLitCon (NoRepStr lit _))
279   = returnTc (Literal (NoRepStr lit stringTy))
280
281 tcUfCon (UfLitCon other_lit)
282   = returnTc (Literal other_lit)
283
284 -- The dreaded lit-lits are also similar, except here the type
285 -- is read in explicitly rather than being implicit
286 tcUfCon (UfLitLitCon lit ty)
287   = tcHsType ty         `thenTc` \ ty' ->
288     returnTc (Literal (MachLitLit lit ty'))
289
290 tcUfCon (UfDataCon name) = tcUfDataCon name
291
292 tcUfCon (UfPrimOp name)
293   = tcVar name          `thenTc` \ op_id ->
294     case isPrimitiveId_maybe op_id of
295         Just op -> returnTc (PrimOp op)
296         Nothing -> failWithTc (badPrimOp name)
297
298 tcUfCon (UfCCallOp str is_dyn casm gc)
299   = case is_dyn of
300        True  -> 
301           tcGetUnique `thenNF_Tc` \ u ->
302           returnTc (PrimOp (CCallOp (Right u) casm gc cCallConv))
303        False -> returnTc (PrimOp (CCallOp (Left str) casm gc cCallConv))
304
305 tcUfDataCon name
306   = tcVar name          `thenTc` \ con_id ->
307     case isDataConId_maybe con_id of
308         Just con -> returnTc (DataCon con)
309         Nothing  -> failWithTc (badCon name)
310 \end{code}
311
312 \begin{code}
313 tcCoreLamBndr (UfValBinder name ty) thing_inside
314   = tcHsType ty                 `thenTc` \ ty' ->
315     let
316         id = mkVanillaId name ty'
317     in
318     tcExtendGlobalValEnv [id] $
319     thing_inside id
320     
321 tcCoreLamBndr (UfTyBinder name kind) thing_inside
322   = let
323         tyvar = mkTyVar name kind
324     in
325     tcExtendTyVarEnv [tyvar] (thing_inside tyvar)
326     
327 tcCoreLamBndrs []     thing_inside = thing_inside []
328 tcCoreLamBndrs (b:bs) thing_inside
329   = tcCoreLamBndr b     $ \ b' ->
330     tcCoreLamBndrs bs   $ \ bs' ->
331     thing_inside (b':bs')
332
333 tcCoreValBndr (UfValBinder name ty) thing_inside
334   = tcHsType ty                 `thenTc` \ ty' ->
335     let
336         id = mkVanillaId name ty'
337     in
338     tcExtendGlobalValEnv [id] $
339     thing_inside id
340     
341 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
342   = mapTc tcHsType tys                  `thenTc` \ tys' ->
343     let
344         ids = zipWithEqual "tcCoreValBndr" mkVanillaId names tys'
345     in
346     tcExtendGlobalValEnv ids $
347     thing_inside ids
348   where
349     names = [name | UfValBinder name _  <- bndrs]
350     tys   = [ty   | UfValBinder _    ty <- bndrs]
351 \end{code}    
352
353 \begin{code}
354 tcCoreAlt scrut_ty (UfDefault, names, rhs)
355   = ASSERT( null names )
356     tcCoreExpr rhs              `thenTc` \ rhs' ->
357     returnTc (DEFAULT, [], rhs')
358   
359 tcCoreAlt scrut_ty (UfLitCon lit, names, rhs)
360   = ASSERT( null names )
361     tcCoreExpr rhs              `thenTc` \ rhs' ->
362     returnTc (Literal lit, [], rhs')
363
364 tcCoreAlt scrut_ty (UfLitLitCon str ty, names, rhs)
365   = ASSERT( null names )
366     tcCoreExpr rhs              `thenTc` \ rhs' ->
367     tcHsType ty                 `thenTc` \ ty' ->
368     returnTc (Literal (MachLitLit str ty'), [], rhs')
369
370 -- A case alternative is made quite a bit more complicated
371 -- by the fact that we omit type annotations because we can
372 -- work them out.  True enough, but its not that easy!
373 tcCoreAlt scrut_ty (UfDataCon con_name, names, rhs)
374   = tcVar con_name              `thenTc` \ con_id ->
375     let
376         con                     = case isDataConId_maybe con_id of
377                                         Just con -> con
378                                         Nothing  -> pprPanic "tcCoreAlt" (ppr con_id)
379
380         (main_tyvars, _, ex_tyvars, _, _, _) = dataConSig con
381
382         (tycon, inst_tys, cons) = splitAlgTyConApp scrut_ty
383         ex_tyvars'              = [mkTyVar name (tyVarKind tv) | (name,tv) <- names `zip` ex_tyvars] 
384         ex_tys'                 = mkTyVarTys ex_tyvars'
385         arg_tys                 = dataConArgTys con (inst_tys ++ ex_tys')
386         id_names                = drop (length ex_tyvars) names
387         arg_ids
388 #ifdef DEBUG
389                 | length id_names /= length arg_tys
390                 = pprPanic "tcCoreAlts" (ppr (con_name, names, rhs) $$
391                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
392                                          ppr arg_tys)
393                 | otherwise
394 #endif
395                 = zipWithEqual "tcCoreAlts" mkVanillaId id_names arg_tys
396     in
397     ASSERT( con `elem` cons && length inst_tys == length main_tyvars )
398     tcExtendTyVarEnv ex_tyvars'                 $
399     tcExtendGlobalValEnv arg_ids                $
400     tcCoreExpr rhs                                      `thenTc` \ rhs' ->
401     returnTc (DataCon con, ex_tyvars' ++ arg_ids, rhs')
402 \end{code}
403
404 \begin{code}
405 ifaceSigCtxt sig_name
406   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
407 \end{code}
408