[project @ 1999-04-13 08:55:33 by kglynn]
[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 ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( HsDecl(..), IfaceSig(..) )
12 import TcMonad
13 import TcMonoType       ( tcHsType, tcHsTypeKind, 
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                           tcExtendTyVarScope
18                         )
19 import TcEnv            ( ValueEnv, tcExtendTyVarEnv, 
20                           tcExtendGlobalValEnv, tcSetValueEnv,
21                           tcLookupTyConByKey, tcLookupValueMaybe,
22                           explicitLookupValue, badCon, badPrimOp
23                         )
24 import TcType           ( TcKind, kindToTcKind )
25
26 import RnHsSyn          ( RenamedHsDecl )
27 import HsCore
28 import HsDecls          ( HsIdInfo(..), HsStrictnessInfo(..) )
29 import CallConv         ( cCallConv )
30 import Const            ( Con(..), Literal(..) )
31 import CoreSyn
32 import CoreUtils        ( coreExprType )
33 import CoreUnfold
34 import CoreLint         ( lintUnfolding )
35 import WwLib            ( mkWrapper )
36 import PrimOp           ( PrimOp(..) )
37
38 import Id               ( Id, mkImportedId, mkUserId,
39                           isPrimitiveId_maybe, isDataConId_maybe
40                         )
41 import IdInfo
42 import DataCon          ( dataConSig, dataConArgTys )
43 import SpecEnv          ( addToSpecEnv )
44 import Type             ( mkSynTy, mkTyVarTys, splitAlgTyConApp )
45 import Var              ( IdOrTyVar, mkTyVar, tyVarKind )
46 import VarEnv
47 import Name             ( Name, NamedThing(..) )
48 import Unique           ( rationalTyConKey )
49 import TysWiredIn       ( integerTy, stringTy )
50 import ErrUtils         ( pprBagOfErrors )
51 import Maybes           ( maybeToBool, MaybeErr(..) )
52 import Outputable       
53 import Util             ( zipWithEqual )
54 \end{code}
55
56 Ultimately, type signatures in interfaces will have pragmatic
57 information attached, so it is a good idea to have separate code to
58 check them.
59
60 As always, we do not have to worry about user-pragmas in interface
61 signatures.
62
63 \begin{code}
64 tcInterfaceSigs :: ValueEnv             -- Envt to use when checking unfoldings
65                 -> [RenamedHsDecl]      -- Ignore non-sig-decls in these decls
66                 -> TcM s [Id]
67                 
68
69 tcInterfaceSigs unf_env (SigD (IfaceSig name ty id_infos src_loc) : rest)
70   = tcAddSrcLoc src_loc (
71     tcAddErrCtxt (ifaceSigCtxt name) (
72         tcHsType ty                                             `thenTc` \ sigma_ty ->
73         tcIdInfo unf_env name sigma_ty noIdInfo id_infos        `thenTc` \ id_info ->
74         returnTc (mkImportedId name sigma_ty id_info)
75     ))                                          `thenTc` \ sig_id ->
76     tcInterfaceSigs unf_env rest                `thenTc` \ sig_ids ->
77     returnTc (sig_id : sig_ids)
78
79 tcInterfaceSigs unf_env (other_decl : rest) = tcInterfaceSigs unf_env rest
80
81 tcInterfaceSigs unf_env [] = returnTc []
82 \end{code}
83
84 \begin{code}
85 tcIdInfo unf_env name ty info info_ins
86   = foldlTc tcPrag noIdInfo info_ins
87   where
88     tcPrag info (HsArity arity) = returnTc (arity `setArityInfo` info)
89     tcPrag info (HsUpdate upd)  = returnTc (upd   `setUpdateInfo` info)
90     tcPrag info (HsNoCafRefs)   = returnTc (NoCafRefs `setCafInfo` info)
91     tcPrag info (HsCprInfo cpr_info)     = returnTc (cpr_info `setCprInfo` info)
92
93     tcPrag info (HsUnfold inline_prag maybe_expr)
94         = (case maybe_expr of
95                 Just expr -> tcPragExpr unf_env name [] expr
96                 Nothing   -> returnNF_Tc Nothing
97           )                                     `thenNF_Tc` \ maybe_expr' ->
98           let
99                 -- maybe_expr doesn't get looked at if the unfolding
100                 -- is never inspected; so the typecheck doesn't even happen
101                 unfold_info = case maybe_expr' of
102                                 Nothing    -> NoUnfolding
103                                 Just expr' -> mkUnfolding expr' 
104                 info1 = unfold_info `setUnfoldingInfo` info
105
106                 info2 = inline_prag `setInlinePragInfo` info1
107           in
108           returnTc info2
109
110     tcPrag info (HsStrictness strict)
111         = tcStrictness unf_env ty info strict
112
113     tcPrag info (HsSpecialise tyvars tys rhs)
114         = tcExtendTyVarScope tyvars             $ \ tyvars' ->
115           mapAndUnzipTc tcHsTypeKind tys        `thenTc` \ (kinds, tys') -> 
116                 -- Assume that the kinds match the kinds of the 
117                 -- type variables of the function; this is, after all, an
118                 -- interface file generated by the compiler!
119
120           tcPragExpr unf_env name tyvars' rhs   `thenNF_Tc` \ maybe_rhs' ->
121           let
122                 -- If spec_env isn't looked at, none of this 
123                 -- actually takes place
124             spec_env  = specInfo info
125             spec_env' = case maybe_rhs' of
126                           Nothing -> spec_env
127                           Just rhs' -> case addToSpecEnv True {- overlap ok -} spec_env tyvars' tys' rhs' of
128                                           Succeeded spec_env' -> spec_env'
129                                           Failed err          -> pprTrace "tcIdInfo: bad specialisation"
130                                                                           (ppr name <+> ppr err) $
131                                                                  spec_env
132           in
133           returnTc (spec_env' `setSpecInfo` info)
134 \end{code}
135
136 \begin{code}
137 tcStrictness unf_env ty info (HsStrictnessInfo (demands, bot_result) maybe_worker)
138   = tcWorker unf_env maybe_worker               `thenNF_Tc` \ maybe_worker_id ->
139     -- We are relying here on cpr info always appearing before strictness info
140     -- fingers crossed ....
141     uniqSMToTcM (mkWrapper ty demands (cprInfo info))
142                                                 `thenNF_Tc` \ wrap_fn ->
143     let
144         -- Watch out! We can't pull on maybe_worker_id too eagerly!
145         info' = case maybe_worker_id of
146                         Just worker_id -> setUnfoldingInfo (mkUnfolding (wrap_fn worker_id)) $
147                                           setWorkerInfo (Just worker_id) $
148                                           setInlinePragInfo IWantToBeINLINEd info
149
150                         Nothing        -> info
151
152         has_worker = maybeToBool maybe_worker_id
153     in
154     returnTc (StrictnessInfo demands bot_result `setStrictnessInfo` info')
155 \end{code}
156
157 \begin{code}
158 tcWorker unf_env Nothing = returnNF_Tc Nothing
159
160 tcWorker unf_env (Just (worker_name,_))
161   = returnNF_Tc (trace_maybe maybe_worker_id)
162   where
163     maybe_worker_id = explicitLookupValue unf_env worker_name
164
165         -- The trace is so we can see what's getting dropped
166     trace_maybe Nothing  = pprTrace "tcWorker failed:" (ppr worker_name) Nothing
167     trace_maybe (Just x) = Just x
168 \end{code}
169
170 For unfoldings we try to do the job lazily, so that we never type check
171 an unfolding that isn't going to be looked at.
172
173 \begin{code}
174 tcPragExpr :: ValueEnv -> Name -> [IdOrTyVar] -> UfExpr Name -> NF_TcM s (Maybe CoreExpr)
175 tcPragExpr unf_env name in_scope_vars core_expr
176   = forkNF_Tc (
177         recoverNF_Tc no_unfolding (
178                 tcSetValueEnv unf_env $
179                 tcCoreExpr core_expr    `thenTc` \ core_expr' ->
180
181                 -- Check for type consistency in the unfolding
182                 tcGetSrcLoc             `thenNF_Tc` \ src_loc -> 
183                 returnTc (lintUnfolding src_loc in_scope_vars core_expr')
184     ))                  
185   where
186         -- The trace tells what wasn't available, for the benefit of
187         -- compiler hackers who want to improve it!
188     no_unfolding = getErrsTc            `thenNF_Tc` \ (warns,errs) ->
189                    returnNF_Tc (pprTrace "tcUnfolding failed with:" 
190                                          (hang (ppr name) 4 (pprBagOfErrors errs))
191                                          Nothing)
192 \end{code}
193
194
195 Variables in unfoldings
196 ~~~~~~~~~~~~~~~~~~~~~~~
197 ****** Inside here we use only the Global environment, even for locally bound variables.
198 ****** Why? Because we know all the types and want to bind them to real Ids.
199
200 \begin{code}
201 tcVar :: Name -> TcM s Id
202 tcVar name
203   = tcLookupValueMaybe name     `thenNF_Tc` \ maybe_id ->
204     case maybe_id of {
205         Just id -> returnTc id;
206         Nothing -> failWithTc (noDecl name)
207     }
208
209 noDecl name = hsep [ptext SLIT("Warning: no binding for"), ppr name]
210 \end{code}
211
212 UfCore expressions.
213
214 \begin{code}
215 tcCoreExpr :: UfExpr Name -> TcM s CoreExpr
216
217 tcCoreExpr (UfType ty)
218   = tcHsTypeKind ty     `thenTc` \ (_, ty') ->
219         -- It might not be of kind type
220     returnTc (Type ty')
221
222 tcCoreExpr (UfVar name)
223   = tcVar name  `thenTc` \ id ->
224     returnTc (Var id)
225
226 tcCoreExpr (UfCon con args) 
227   = tcUfCon con                 `thenTc` \ con' ->
228     mapTc tcCoreExpr args       `thenTc` \ args' ->
229     returnTc (Con con' args')
230
231 tcCoreExpr (UfTuple name args) 
232   = tcUfDataCon name            `thenTc` \ con ->
233     mapTc tcCoreExpr args       `thenTc` \ args' ->
234     let
235         -- Put the missing type arguments back in
236         con_args = map (Type . coreExprType) args' ++ args'
237     in
238     returnTc (Con con con_args)
239
240 tcCoreExpr (UfLam bndr body)
241   = tcCoreLamBndr bndr          $ \ bndr' ->
242     tcCoreExpr body             `thenTc` \ body' ->
243     returnTc (Lam bndr' body')
244
245 tcCoreExpr (UfApp fun arg)
246   = tcCoreExpr fun              `thenTc` \ fun' ->
247     tcCoreExpr arg              `thenTc` \ arg' ->
248     returnTc (App fun' arg')
249
250 tcCoreExpr (UfCase scrut case_bndr alts) 
251   = tcCoreExpr scrut                                    `thenTc` \ scrut' ->
252     let
253         scrut_ty = coreExprType scrut'
254         case_bndr' = mkUserId case_bndr scrut_ty
255     in
256     tcExtendGlobalValEnv [case_bndr']   $
257     mapTc (tcCoreAlt scrut_ty) alts     `thenTc` \ alts' ->
258     returnTc (Case scrut' case_bndr' alts')
259
260 tcCoreExpr (UfLet (UfNonRec bndr rhs) body)
261   = tcCoreExpr rhs              `thenTc` \ rhs' ->
262     tcCoreValBndr bndr          $ \ bndr' ->
263     tcCoreExpr body             `thenTc` \ body' ->
264     returnTc (Let (NonRec bndr' rhs') body')
265
266 tcCoreExpr (UfLet (UfRec pairs) body)
267   = tcCoreValBndrs bndrs        $ \ bndrs' ->
268     mapTc tcCoreExpr rhss       `thenTc` \ rhss' ->
269     tcCoreExpr body             `thenTc` \ body' ->
270     returnTc (Let (Rec (bndrs' `zip` rhss')) body')
271   where
272     (bndrs, rhss) = unzip pairs
273
274 tcCoreExpr (UfNote note expr) 
275   = tcCoreExpr expr             `thenTc` \ expr' ->
276     case note of
277         UfCoerce to_ty -> tcHsType to_ty        `thenTc` \ to_ty' ->
278                           returnTc (Note (Coerce to_ty' (coreExprType expr')) expr')
279         UfInlineCall   -> returnTc (Note InlineCall expr')
280         UfSCC cc       -> returnTc (Note (SCC cc) expr')
281
282 tcCoreNote (UfSCC cc)   = returnTc (SCC cc)
283 tcCoreNote UfInlineCall = returnTc InlineCall 
284
285
286 -- rationalTy isn't built in so, we have to construct it
287 -- (the "ty" part of the incoming literal is simply bottom)
288 tcUfCon (UfLitCon (NoRepRational lit _)) 
289   = tcLookupTyConByKey rationalTyConKey `thenNF_Tc` \ rational_tycon ->
290     let
291         rational_ty  = mkSynTy rational_tycon []
292     in
293     returnTc (Literal (NoRepRational lit rational_ty)) 
294
295 -- Similarly for integers and strings, except that they are wired in
296 tcUfCon (UfLitCon (NoRepInteger lit _)) 
297   = returnTc (Literal (NoRepInteger lit integerTy))
298 tcUfCon (UfLitCon (NoRepStr lit _))
299   = returnTc (Literal (NoRepStr lit stringTy))
300
301 tcUfCon (UfLitCon other_lit)
302   = returnTc (Literal other_lit)
303
304 -- The dreaded lit-lits are also similar, except here the type
305 -- is read in explicitly rather than being implicit
306 tcUfCon (UfLitLitCon lit ty)
307   = tcHsType ty         `thenTc` \ ty' ->
308     returnTc (Literal (MachLitLit lit ty'))
309
310 tcUfCon (UfDataCon name) = tcUfDataCon name
311
312 tcUfCon (UfPrimOp name)
313   = tcVar name          `thenTc` \ op_id ->
314     case isPrimitiveId_maybe op_id of
315         Just op -> returnTc (PrimOp op)
316         Nothing -> failWithTc (badPrimOp name)
317
318 tcUfCon (UfCCallOp str is_dyn casm gc)
319   = case is_dyn of
320        True  -> 
321           tcGetUnique `thenNF_Tc` \ u ->
322           returnTc (PrimOp (CCallOp (Right u) casm gc cCallConv))
323        False -> returnTc (PrimOp (CCallOp (Left str) casm gc cCallConv))
324
325 tcUfDataCon name
326   = tcVar name          `thenTc` \ con_id ->
327     case isDataConId_maybe con_id of
328         Just con -> returnTc (DataCon con)
329         Nothing  -> failWithTc (badCon name)
330 \end{code}
331
332 \begin{code}
333 tcCoreLamBndr (UfValBinder name ty) thing_inside
334   = tcHsType ty                 `thenTc` \ ty' ->
335     let
336         id = mkUserId name ty'
337     in
338     tcExtendGlobalValEnv [id] $
339     thing_inside id
340     
341 tcCoreLamBndr (UfTyBinder name kind) thing_inside
342   = let
343         tyvar = mkTyVar name kind
344     in
345     tcExtendTyVarEnv [tyvar] (thing_inside tyvar)
346     
347 tcCoreValBndr (UfValBinder name ty) thing_inside
348   = tcHsType ty                 `thenTc` \ ty' ->
349     let
350         id = mkUserId name ty'
351     in
352     tcExtendGlobalValEnv [id] $
353     thing_inside id
354     
355 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
356   = mapTc tcHsType tys                  `thenTc` \ tys' ->
357     let
358         ids = zipWithEqual "tcCoreValBndr" mkUserId names tys'
359     in
360     tcExtendGlobalValEnv ids $
361     thing_inside ids
362   where
363     names = [name | UfValBinder name _  <- bndrs]
364     tys   = [ty   | UfValBinder _    ty <- bndrs]
365 \end{code}    
366
367 \begin{code}
368 tcCoreAlt scrut_ty (UfDefault, names, rhs)
369   = ASSERT( null names )
370     tcCoreExpr rhs              `thenTc` \ rhs' ->
371     returnTc (DEFAULT, [], rhs')
372   
373 tcCoreAlt scrut_ty (UfLitCon lit, names, rhs)
374   = ASSERT( null names )
375     tcCoreExpr rhs              `thenTc` \ rhs' ->
376     returnTc (Literal lit, [], rhs')
377
378 tcCoreAlt scrut_ty (UfLitLitCon str ty, names, rhs)
379   = ASSERT( null names )
380     tcCoreExpr rhs              `thenTc` \ rhs' ->
381     tcHsType ty                 `thenTc` \ ty' ->
382     returnTc (Literal (MachLitLit str ty'), [], rhs')
383
384 -- A case alternative is made quite a bit more complicated
385 -- by the fact that we omit type annotations because we can
386 -- work them out.  True enough, but its not that easy!
387 tcCoreAlt scrut_ty (UfDataCon con_name, names, rhs)
388   = tcVar con_name              `thenTc` \ con_id ->
389     let
390         con                     = case isDataConId_maybe con_id of
391                                         Just con -> con
392                                         Nothing  -> pprPanic "tcCoreAlt" (ppr con_id)
393
394         (main_tyvars, _, ex_tyvars, _, _, _) = dataConSig con
395
396         (tycon, inst_tys, cons) = splitAlgTyConApp scrut_ty
397         ex_tyvars'              = [mkTyVar name (tyVarKind tv) | (name,tv) <- names `zip` ex_tyvars] 
398         ex_tys'                 = mkTyVarTys ex_tyvars'
399         arg_tys                 = dataConArgTys con (inst_tys ++ ex_tys')
400         id_names                = drop (length ex_tyvars) names
401         arg_ids
402 #ifdef DEBUG
403                 | length id_names /= length arg_tys
404                 = pprPanic "tcCoreAlts" (ppr (con_name, names, rhs) $$
405                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
406                                          ppr arg_tys)
407                 | otherwise
408 #endif
409                 = zipWithEqual "tcCoreAlts" mkUserId id_names arg_tys
410     in
411     ASSERT( con `elem` cons && length inst_tys == length main_tyvars )
412     tcExtendTyVarEnv ex_tyvars'                 $
413     tcExtendGlobalValEnv arg_ids                $
414     tcCoreExpr rhs                                      `thenTc` \ rhs' ->
415     returnTc (DataCon con, ex_tyvars' ++ arg_ids, rhs')
416 \end{code}
417
418 \begin{code}
419 ifaceSigCtxt sig_name
420   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
421 \end{code}
422