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