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