[project @ 2000-10-31 09:58:13 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(..), TyClDecl(..), 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, RecTcEnv, tcExtendTyVarEnv, 
19                           tcExtendGlobalValEnv, tcSetEnv,
20                           tcLookupGlobal_maybe, tcLookupRecId, 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 :: RecTcEnv             -- 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            | TyClD (IfaceSig name ty id_infos src_loc) <- decls]
62   where
63     in_scope_vars = []  -- I think this will be OK
64                         -- If so, don't pass it around
65                         -- Was: filter isLocallyDefined (tcEnvIds 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 tcLookupRecId 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         getDOptsTc              `thenTc` \ dflags ->
142         case lintUnfolding dflags 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 :: RecTcEnv -> SDoc -> TcM a -> NF_TcM (Maybe a)
149 tcDelay unf_env doc thing_inside
150   = forkNF_Tc (
151         recoverNF_Tc bad_value (
152                 tcSetEnv 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 Id
172 tcVar name
173   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_id ->
174     case maybe_id of {
175         Just (AnId 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 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 \end{code}
263
264 \begin{code}
265 tcCoreLamBndr (UfValBinder name ty) thing_inside
266   = tcHsType ty                 `thenTc` \ ty' ->
267     let
268         id = mkVanillaId name ty'
269     in
270     tcExtendGlobalValEnv [id] $
271     thing_inside id
272     
273 tcCoreLamBndr (UfTyBinder name kind) thing_inside
274   = let
275         tyvar = mkTyVar name kind
276     in
277     tcExtendTyVarEnv [tyvar] (thing_inside tyvar)
278     
279 tcCoreLamBndrs []     thing_inside = thing_inside []
280 tcCoreLamBndrs (b:bs) thing_inside
281   = tcCoreLamBndr b     $ \ b' ->
282     tcCoreLamBndrs bs   $ \ bs' ->
283     thing_inside (b':bs')
284
285 tcCoreValBndr (UfValBinder name ty) thing_inside
286   = tcHsType ty                 `thenTc` \ ty' ->
287     let
288         id = mkVanillaId name ty'
289     in
290     tcExtendGlobalValEnv [id] $
291     thing_inside id
292     
293 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
294   = mapTc tcHsType tys                  `thenTc` \ tys' ->
295     let
296         ids = zipWithEqual "tcCoreValBndr" mkVanillaId names tys'
297     in
298     tcExtendGlobalValEnv ids $
299     thing_inside ids
300   where
301     names = [name | UfValBinder name _  <- bndrs]
302     tys   = [ty   | UfValBinder _    ty <- bndrs]
303 \end{code}    
304
305 \begin{code}
306 tcCoreAlt scrut_ty (UfDefault, names, rhs)
307   = ASSERT( null names )
308     tcCoreExpr rhs              `thenTc` \ rhs' ->
309     returnTc (DEFAULT, [], rhs')
310   
311 tcCoreAlt scrut_ty (UfLitAlt lit, names, rhs)
312   = ASSERT( null names )
313     tcCoreExpr rhs              `thenTc` \ rhs' ->
314     returnTc (LitAlt lit, [], rhs')
315
316 tcCoreAlt scrut_ty (UfLitLitAlt str ty, names, rhs)
317   = ASSERT( null names )
318     tcCoreExpr rhs              `thenTc` \ rhs' ->
319     tcHsType ty                 `thenTc` \ ty' ->
320     returnTc (LitAlt (MachLitLit str ty'), [], rhs')
321
322 -- A case alternative is made quite a bit more complicated
323 -- by the fact that we omit type annotations because we can
324 -- work them out.  True enough, but its not that easy!
325 tcCoreAlt scrut_ty alt@(UfDataAlt con_name, names, rhs)
326   = tcVar con_name              `thenTc` \ con_id ->
327     let
328         con = case isDataConWrapId_maybe con_id of
329                 Just con -> con
330                 Nothing  -> pprPanic "tcCoreAlt" (ppr con_id)
331
332         (main_tyvars, _, ex_tyvars, _, _, _) = dataConSig con
333
334         (_, inst_tys, cons) = case splitAlgTyConApp_maybe scrut_ty of
335                                     Just stuff -> stuff
336                                     Nothing -> pprPanic "tcCoreAlt" (ppr alt)
337         ex_tyvars'          = [mkTyVar name (tyVarKind tv) | (name,tv) <- names `zip` ex_tyvars] 
338         ex_tys'             = mkTyVarTys ex_tyvars'
339         arg_tys             = dataConArgTys con (inst_tys ++ ex_tys')
340         id_names            = drop (length ex_tyvars) names
341         arg_ids
342 #ifdef DEBUG
343                 | length id_names /= length arg_tys
344                 = pprPanic "tcCoreAlts" (ppr (con_name, names, rhs) $$
345                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
346                                          ppr arg_tys)
347                 | otherwise
348 #endif
349                 = zipWithEqual "tcCoreAlts" mkVanillaId id_names arg_tys
350     in
351     ASSERT( con `elem` cons && length inst_tys == length main_tyvars )
352     tcExtendTyVarEnv ex_tyvars'                 $
353     tcExtendGlobalValEnv arg_ids                $
354     tcCoreExpr rhs                                      `thenTc` \ rhs' ->
355     returnTc (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
356 \end{code}
357
358 \begin{code}
359 ifaceSigCtxt sig_name
360   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
361 \end{code}
362