f1a747f9fa3730f0f4f58dcb94a5870b6b7a2126
[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
261 tcCoreNote (UfSCC cc)   = returnTc (SCC cc)
262 tcCoreNote UfInlineCall = returnTc InlineCall 
263 \end{code}
264
265 \begin{code}
266 tcCoreLamBndr (UfValBinder name ty) thing_inside
267   = tcHsType ty                 `thenTc` \ ty' ->
268     let
269         id = mkVanillaId name ty'
270     in
271     tcExtendGlobalValEnv [id] $
272     thing_inside id
273     
274 tcCoreLamBndr (UfTyBinder name kind) thing_inside
275   = let
276         tyvar = mkTyVar name kind
277     in
278     tcExtendTyVarEnv [tyvar] (thing_inside tyvar)
279     
280 tcCoreLamBndrs []     thing_inside = thing_inside []
281 tcCoreLamBndrs (b:bs) thing_inside
282   = tcCoreLamBndr b     $ \ b' ->
283     tcCoreLamBndrs bs   $ \ bs' ->
284     thing_inside (b':bs')
285
286 tcCoreValBndr (UfValBinder name ty) thing_inside
287   = tcHsType ty                 `thenTc` \ ty' ->
288     let
289         id = mkVanillaId name ty'
290     in
291     tcExtendGlobalValEnv [id] $
292     thing_inside id
293     
294 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
295   = mapTc tcHsType tys                  `thenTc` \ tys' ->
296     let
297         ids = zipWithEqual "tcCoreValBndr" mkVanillaId names tys'
298     in
299     tcExtendGlobalValEnv ids $
300     thing_inside ids
301   where
302     names = [name | UfValBinder name _  <- bndrs]
303     tys   = [ty   | UfValBinder _    ty <- bndrs]
304 \end{code}    
305
306 \begin{code}
307 tcCoreAlt scrut_ty (UfDefault, names, rhs)
308   = ASSERT( null names )
309     tcCoreExpr rhs              `thenTc` \ rhs' ->
310     returnTc (DEFAULT, [], rhs')
311   
312 tcCoreAlt scrut_ty (UfLitAlt lit, names, rhs)
313   = ASSERT( null names )
314     tcCoreExpr rhs              `thenTc` \ rhs' ->
315     returnTc (LitAlt lit, [], rhs')
316
317 tcCoreAlt scrut_ty (UfLitLitAlt str ty, names, rhs)
318   = ASSERT( null names )
319     tcCoreExpr rhs              `thenTc` \ rhs' ->
320     tcHsType ty                 `thenTc` \ ty' ->
321     returnTc (LitAlt (MachLitLit str ty'), [], rhs')
322
323 -- A case alternative is made quite a bit more complicated
324 -- by the fact that we omit type annotations because we can
325 -- work them out.  True enough, but its not that easy!
326 tcCoreAlt scrut_ty alt@(UfDataAlt con_name, names, rhs)
327   = tcVar con_name              `thenTc` \ con_id ->
328     let
329         con = case isDataConWrapId_maybe con_id of
330                 Just con -> con
331                 Nothing  -> pprPanic "tcCoreAlt" (ppr con_id)
332
333         (main_tyvars, _, ex_tyvars, _, _, _) = dataConSig con
334
335         (_, inst_tys, cons) = case splitAlgTyConApp_maybe scrut_ty of
336                                     Just stuff -> stuff
337                                     Nothing -> pprPanic "tcCoreAlt" (ppr alt)
338         ex_tyvars'          = [mkTyVar name (tyVarKind tv) | (name,tv) <- names `zip` ex_tyvars] 
339         ex_tys'             = mkTyVarTys ex_tyvars'
340         arg_tys             = dataConArgTys con (inst_tys ++ ex_tys')
341         id_names            = drop (length ex_tyvars) names
342         arg_ids
343 #ifdef DEBUG
344                 | length id_names /= length arg_tys
345                 = pprPanic "tcCoreAlts" (ppr (con_name, names, rhs) $$
346                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
347                                          ppr arg_tys)
348                 | otherwise
349 #endif
350                 = zipWithEqual "tcCoreAlts" mkVanillaId id_names arg_tys
351     in
352     ASSERT( con `elem` cons && length inst_tys == length main_tyvars )
353     tcExtendTyVarEnv ex_tyvars'                 $
354     tcExtendGlobalValEnv arg_ids                $
355     tcCoreExpr rhs                                      `thenTc` \ rhs' ->
356     returnTc (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
357 \end{code}
358
359 \begin{code}
360 ifaceSigCtxt sig_name
361   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
362 \end{code}
363