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