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