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