[project @ 2001-03-08 12:07:38 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             ( mkCCallOpId )
31 import IdInfo
32 import DataCon          ( DataCon, dataConId, dataConSig, dataConArgTys )
33 import Type             ( mkTyVarTys, splitAlgTyConApp_maybe )
34 import TysWiredIn       ( tupleCon )
35 import Var              ( mkTyVar, tyVarKind )
36 import Name             ( Name, nameIsLocalOrFrom )
37 import Demand           ( wwLazy )
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 vanillaIdInfo info_ins
83   where
84     tcPrag info (HsArity arity) = returnTc (info `setArityInfo`  arity)
85     tcPrag info (HsNoCafRefs)   = returnTc (info `setCafInfo`    NoCafRefs)
86     tcPrag info HsCprInfo       = returnTc (info `setCprInfo`    ReturnsCPR)
87
88     tcPrag info (HsUnfold inline_prag expr)
89         = tcPragExpr unf_env name in_scope_vars expr    `thenNF_Tc` \ maybe_expr' ->
90           let
91                 -- maybe_expr doesn't get looked at if the unfolding
92                 -- is never inspected; so the typecheck doesn't even happen
93                 unfold_info = case maybe_expr' of
94                                 Nothing    -> noUnfolding
95                                 Just expr' -> mkTopUnfolding expr' 
96                 info1 = info `setUnfoldingInfo` unfold_info
97                 info2 = info1 `setInlinePragInfo` inline_prag
98           in
99           returnTc info2
100
101     tcPrag info (HsStrictness strict_info)
102         = returnTc (info `setStrictnessInfo` strict_info)
103
104     tcPrag info (HsWorker nm)
105         = tcWorkerInfo unf_env ty info nm
106 \end{code}
107
108 \begin{code}
109 tcWorkerInfo unf_env ty info worker_name
110   | not (hasArity arity_info)
111   = pprPanic "Worker with no arity info" (ppr worker_name)
112  
113   | otherwise
114   = uniqSMToTcM (mkWrapper ty arity demands res_bot cpr_info) `thenNF_Tc` \ wrap_fn ->
115     let
116         -- Watch out! We can't pull on unf_env too eagerly!
117         info' = case tcLookupRecId_maybe unf_env worker_name of
118                   Just worker_id -> info `setUnfoldingInfo`  mkTopUnfolding (wrap_fn worker_id)
119                                          `setWorkerInfo`     HasWorker worker_id arity
120
121                   Nothing        -> pprTrace "tcWorkerInfo failed:" (ppr worker_name) info
122     in
123     returnTc info'
124   where
125         -- We are relying here on arity, cpr and strictness info always appearing 
126         -- before worker info,  fingers crossed ....
127       arity_info = arityInfo info
128       arity      = arityLowerBound arity_info
129       cpr_info   = cprInfo info
130       (demands, res_bot)    = case strictnessInfo info of
131                                 StrictnessInfo d r -> (d,r)
132                                 _                  -> (take arity (repeat wwLazy),False)        -- Noncommittal
133 \end{code}
134
135 For unfoldings we try to do the job lazily, so that we never type check
136 an unfolding that isn't going to be looked at.
137
138 \begin{code}
139 tcPragExpr unf_env name in_scope_vars expr
140   = tcDelay unf_env doc $
141         tcCoreExpr expr         `thenTc` \ core_expr' ->
142
143                 -- Check for type consistency in the unfolding
144         tcGetSrcLoc             `thenNF_Tc` \ src_loc -> 
145         getDOptsTc              `thenTc` \ dflags ->
146         case lintUnfolding dflags src_loc in_scope_vars core_expr' of
147           (Nothing,_)       -> returnTc core_expr'  -- ignore warnings
148           (Just fail_msg,_) -> failWithTc ((doc <+> text "failed Lint") $$ fail_msg)
149   where
150     doc = text "unfolding of" <+> ppr name
151
152 tcDelay :: RecTcEnv -> SDoc -> TcM a -> NF_TcM (Maybe a)
153 tcDelay unf_env doc thing_inside
154   = forkNF_Tc (
155         recoverNF_Tc bad_value (
156                 tcSetEnv unf_env thing_inside   `thenTc` \ r ->
157                 returnTc (Just r)
158     ))                  
159   where
160         -- The trace tells what wasn't available, for the benefit of
161         -- compiler hackers who want to improve it!
162     bad_value = getErrsTc               `thenNF_Tc` \ (warns,errs) ->
163                 returnNF_Tc (pprTrace "Failed:" 
164                                          (hang doc 4 (pprBagOfErrors errs))
165                                          Nothing)
166 \end{code}
167
168
169 Variables in unfoldings
170 ~~~~~~~~~~~~~~~~~~~~~~~
171 ****** Inside here we use only the Global environment, even for locally bound variables.
172 ****** Why? Because we know all the types and want to bind them to real Ids.
173
174 \begin{code}
175 tcVar :: Name -> TcM Id
176 tcVar name
177   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_id ->
178     case maybe_id of {
179         Just (AnId id)  -> returnTc id ;
180         Nothing         -> failWithTc (noDecl name)
181     }
182
183 noDecl name = hsep [ptext SLIT("Warning: no binding for"), ppr name]
184 \end{code}
185
186 UfCore expressions.
187
188 \begin{code}
189 tcCoreExpr :: UfExpr Name -> TcM CoreExpr
190
191 tcCoreExpr (UfType ty)
192   = tcIfaceType ty              `thenTc` \ ty' ->
193         -- It might not be of kind type
194     returnTc (Type ty')
195
196 tcCoreExpr (UfVar name)
197   = tcVar name  `thenTc` \ id ->
198     returnTc (Var id)
199
200 tcCoreExpr (UfLit lit)
201   = returnTc (Lit lit)
202
203 -- The dreaded lit-lits are also similar, except here the type
204 -- is read in explicitly rather than being implicit
205 tcCoreExpr (UfLitLit lit ty)
206   = tcIfaceType ty              `thenTc` \ ty' ->
207     returnTc (Lit (MachLitLit lit ty'))
208
209 tcCoreExpr (UfCCall cc ty)
210   = tcIfaceType ty      `thenTc` \ ty' ->
211     tcGetUnique         `thenNF_Tc` \ u ->
212     returnTc (Var (mkCCallOpId u cc ty'))
213
214 tcCoreExpr (UfTuple (HsTupCon _ boxity arity) args) 
215   = mapTc tcCoreExpr args       `thenTc` \ args' ->
216     let
217         -- Put the missing type arguments back in
218         con_args = map (Type . exprType) args' ++ args'
219     in
220     returnTc (mkApps (Var con_id) con_args)
221   where
222     con_id = dataConId (tupleCon boxity arity)
223     
224
225 tcCoreExpr (UfLam bndr body)
226   = tcCoreLamBndr bndr          $ \ bndr' ->
227     tcCoreExpr body             `thenTc` \ body' ->
228     returnTc (Lam bndr' body')
229
230 tcCoreExpr (UfApp fun arg)
231   = tcCoreExpr fun              `thenTc` \ fun' ->
232     tcCoreExpr arg              `thenTc` \ arg' ->
233     returnTc (App fun' arg')
234
235 tcCoreExpr (UfCase scrut case_bndr alts) 
236   = tcCoreExpr scrut                                    `thenTc` \ scrut' ->
237     let
238         scrut_ty = exprType scrut'
239         case_bndr' = mkLocalId case_bndr scrut_ty
240     in
241     tcExtendGlobalValEnv [case_bndr']   $
242     mapTc (tcCoreAlt scrut_ty) alts     `thenTc` \ alts' ->
243     returnTc (Case scrut' case_bndr' alts')
244
245 tcCoreExpr (UfLet (UfNonRec bndr rhs) body)
246   = tcCoreExpr rhs              `thenTc` \ rhs' ->
247     tcCoreValBndr bndr          $ \ bndr' ->
248     tcCoreExpr body             `thenTc` \ body' ->
249     returnTc (Let (NonRec bndr' rhs') body')
250
251 tcCoreExpr (UfLet (UfRec pairs) body)
252   = tcCoreValBndrs bndrs        $ \ bndrs' ->
253     mapTc tcCoreExpr rhss       `thenTc` \ rhss' ->
254     tcCoreExpr body             `thenTc` \ body' ->
255     returnTc (Let (Rec (bndrs' `zip` rhss')) body')
256   where
257     (bndrs, rhss) = unzip pairs
258
259 tcCoreExpr (UfNote note expr) 
260   = tcCoreExpr expr             `thenTc` \ expr' ->
261     case note of
262         UfCoerce to_ty -> tcIfaceType to_ty     `thenTc` \ to_ty' ->
263                           returnTc (Note (Coerce to_ty'
264                                                  (exprType expr')) expr')
265         UfInlineCall   -> returnTc (Note InlineCall expr')
266         UfInlineMe     -> returnTc (Note InlineMe   expr')
267         UfSCC cc       -> returnTc (Note (SCC cc)   expr')
268 \end{code}
269
270 \begin{code}
271 tcCoreLamBndr (UfValBinder name ty) thing_inside
272   = tcIfaceType ty              `thenTc` \ ty' ->
273     let
274         id = mkLocalId name ty'
275     in
276     tcExtendGlobalValEnv [id] $
277     thing_inside id
278     
279 tcCoreLamBndr (UfTyBinder name kind) thing_inside
280   = let
281         tyvar = mkTyVar name kind
282     in
283     tcExtendTyVarEnv [tyvar] (thing_inside tyvar)
284     
285 tcCoreLamBndrs []     thing_inside = thing_inside []
286 tcCoreLamBndrs (b:bs) thing_inside
287   = tcCoreLamBndr b     $ \ b' ->
288     tcCoreLamBndrs bs   $ \ bs' ->
289     thing_inside (b':bs')
290
291 tcCoreValBndr (UfValBinder name ty) thing_inside
292   = tcIfaceType ty                      `thenTc` \ ty' ->
293     let
294         id = mkLocalId name ty'
295     in
296     tcExtendGlobalValEnv [id] $
297     thing_inside id
298     
299 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
300   = mapTc tcIfaceType tys               `thenTc` \ tys' ->
301     let
302         ids = zipWithEqual "tcCoreValBndr" mkLocalId names tys'
303     in
304     tcExtendGlobalValEnv ids $
305     thing_inside ids
306   where
307     names = [name | UfValBinder name _  <- bndrs]
308     tys   = [ty   | UfValBinder _    ty <- bndrs]
309 \end{code}    
310
311 \begin{code}
312 tcCoreAlt scrut_ty (UfDefault, names, rhs)
313   = ASSERT( null names )
314     tcCoreExpr rhs              `thenTc` \ rhs' ->
315     returnTc (DEFAULT, [], rhs')
316   
317 tcCoreAlt scrut_ty (UfLitAlt lit, names, rhs)
318   = ASSERT( null names )
319     tcCoreExpr rhs              `thenTc` \ rhs' ->
320     returnTc (LitAlt lit, [], rhs')
321
322 tcCoreAlt scrut_ty (UfLitLitAlt str ty, names, rhs)
323   = ASSERT( null names )
324     tcCoreExpr rhs              `thenTc` \ rhs' ->
325     tcIfaceType ty              `thenTc` \ ty' ->
326     returnTc (LitAlt (MachLitLit str ty'), [], rhs')
327
328 -- A case alternative is made quite a bit more complicated
329 -- by the fact that we omit type annotations because we can
330 -- work them out.  True enough, but its not that easy!
331 tcCoreAlt scrut_ty alt@(con, names, rhs)
332   = tcConAlt con        `thenTc` \ con ->
333     let
334         (main_tyvars, _, ex_tyvars, _, _, _) = dataConSig con
335
336         (_, inst_tys, cons) = case splitAlgTyConApp_maybe scrut_ty of
337                                     Just stuff -> stuff
338                                     Nothing -> pprPanic "tcCoreAlt" (ppr alt)
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` cons && 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