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