[project @ 2001-02-23 14:59:26 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            ( 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, mkId, mkVanillaId, isLocalId, isDataConWrapId_maybe )
29 import MkId             ( mkCCallOpId )
30 import IdInfo
31 import DataCon          ( DataCon, dataConId, dataConSig, dataConArgTys )
32 import Type             ( mkTyVarTys, splitAlgTyConApp_maybe )
33 import TysWiredIn       ( tupleCon )
34 import Var              ( mkTyVar, tyVarKind )
35 import Name             ( Name )
36 import Demand           ( wwLazy )
37 import ErrUtils         ( pprBagOfErrors )
38 import Outputable       
39 import Util             ( zipWithEqual )
40 import HscTypes         ( TyThing(..) )
41 \end{code}
42
43 Ultimately, type signatures in interfaces will have pragmatic
44 information attached, so it is a good idea to have separate code to
45 check them.
46
47 As always, we do not have to worry about user-pragmas in interface
48 signatures.
49
50 \begin{code}
51 tcInterfaceSigs :: RecTcEnv             -- Envt to use when checking unfoldings
52                 -> [RenamedTyClDecl]    -- Ignore non-sig-decls in these decls
53                 -> TcM [Id]
54                 
55
56 tcInterfaceSigs unf_env decls
57   = listTc [ do_one name ty id_infos src_loc
58            | IfaceSig {tcdName = name, tcdType = ty, tcdIdInfo = id_infos, tcdLoc =src_loc} <- decls]
59   where
60     in_scope_vars = filter isLocalId (tcEnvIds unf_env)
61         -- When we have hi-boot files, an unfolding might refer to
62         -- something defined in this module, so we must build a
63         -- suitable in-scope set.  This thunk will only be poked
64         -- if -dcore-lint is on.
65
66     do_one name ty id_infos src_loc
67       = tcAddSrcLoc src_loc                             $       
68         tcAddErrCtxt (ifaceSigCtxt name)                $
69         tcIfaceType ty                                  `thenTc` \ sigma_ty ->
70         tcIdInfo unf_env in_scope_vars name 
71                  sigma_ty id_infos                      `thenTc` \ id_info ->
72         returnTc (mkId name sigma_ty id_info)
73 \end{code}
74
75 \begin{code}
76 tcIdInfo unf_env in_scope_vars name ty info_ins
77   = foldlTc tcPrag constantIdInfo info_ins
78   where
79     tcPrag info (HsArity arity) = returnTc (info `setArityInfo`  arity)
80     tcPrag info (HsNoCafRefs)   = returnTc (info `setCafInfo`    NoCafRefs)
81     tcPrag info HsCprInfo       = returnTc (info `setCprInfo`    ReturnsCPR)
82
83     tcPrag info (HsUnfold inline_prag expr)
84         = tcPragExpr unf_env name in_scope_vars expr    `thenNF_Tc` \ maybe_expr' ->
85           let
86                 -- maybe_expr doesn't get looked at if the unfolding
87                 -- is never inspected; so the typecheck doesn't even happen
88                 unfold_info = case maybe_expr' of
89                                 Nothing    -> noUnfolding
90                                 Just expr' -> mkTopUnfolding expr' 
91                 info1 = info `setUnfoldingInfo` unfold_info
92                 info2 = info1 `setInlinePragInfo` inline_prag
93           in
94           returnTc info2
95
96     tcPrag info (HsStrictness strict_info)
97         = returnTc (info `setStrictnessInfo` strict_info)
98
99     tcPrag info (HsWorker nm)
100         = tcWorkerInfo unf_env ty info nm
101 \end{code}
102
103 \begin{code}
104 tcWorkerInfo unf_env ty info worker_name
105   | not (hasArity arity_info)
106   = pprPanic "Worker with no arity info" (ppr worker_name)
107  
108   | otherwise
109   = uniqSMToTcM (mkWrapper ty arity demands res_bot cpr_info) `thenNF_Tc` \ wrap_fn ->
110     let
111         -- Watch out! We can't pull on unf_env too eagerly!
112         info' = case tcLookupRecId_maybe unf_env worker_name of
113                   Just worker_id -> info `setUnfoldingInfo`  mkTopUnfolding (wrap_fn worker_id)
114                                          `setWorkerInfo`     HasWorker worker_id arity
115
116                   Nothing        -> pprTrace "tcWorkerInfo failed:" (ppr worker_name) info
117     in
118     returnTc info'
119   where
120         -- We are relying here on arity, cpr and strictness info always appearing 
121         -- before worker info,  fingers crossed ....
122       arity_info = arityInfo info
123       arity      = arityLowerBound arity_info
124       cpr_info   = cprInfo info
125       (demands, res_bot)    = case strictnessInfo info of
126                                 StrictnessInfo d r -> (d,r)
127                                 _                  -> (take arity (repeat wwLazy),False)        -- Noncommittal
128 \end{code}
129
130 For unfoldings we try to do the job lazily, so that we never type check
131 an unfolding that isn't going to be looked at.
132
133 \begin{code}
134 tcPragExpr unf_env name in_scope_vars expr
135   = tcDelay unf_env doc $
136         tcCoreExpr expr         `thenTc` \ core_expr' ->
137
138                 -- Check for type consistency in the unfolding
139         tcGetSrcLoc             `thenNF_Tc` \ src_loc -> 
140         getDOptsTc              `thenTc` \ dflags ->
141         case lintUnfolding dflags src_loc in_scope_vars core_expr' of
142           (Nothing,_)       -> returnTc core_expr'  -- ignore warnings
143           (Just fail_msg,_) -> failWithTc ((doc <+> text "failed Lint") $$ fail_msg)
144   where
145     doc = text "unfolding of" <+> ppr name
146
147 tcDelay :: RecTcEnv -> SDoc -> TcM a -> NF_TcM (Maybe a)
148 tcDelay unf_env doc thing_inside
149   = forkNF_Tc (
150         recoverNF_Tc bad_value (
151                 tcSetEnv unf_env thing_inside   `thenTc` \ r ->
152                 returnTc (Just r)
153     ))                  
154   where
155         -- The trace tells what wasn't available, for the benefit of
156         -- compiler hackers who want to improve it!
157     bad_value = getErrsTc               `thenNF_Tc` \ (warns,errs) ->
158                 returnNF_Tc (pprTrace "Failed:" 
159                                          (hang doc 4 (pprBagOfErrors errs))
160                                          Nothing)
161 \end{code}
162
163
164 Variables in unfoldings
165 ~~~~~~~~~~~~~~~~~~~~~~~
166 ****** Inside here we use only the Global environment, even for locally bound variables.
167 ****** Why? Because we know all the types and want to bind them to real Ids.
168
169 \begin{code}
170 tcVar :: Name -> TcM Id
171 tcVar name
172   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_id ->
173     case maybe_id of {
174         Just (AnId id)  -> returnTc id;
175         Nothing         -> failWithTc (noDecl name)
176     }
177
178 noDecl name = hsep [ptext SLIT("Warning: no binding for"), ppr name]
179 \end{code}
180
181 UfCore expressions.
182
183 \begin{code}
184 tcCoreExpr :: UfExpr Name -> TcM CoreExpr
185
186 tcCoreExpr (UfType ty)
187   = tcIfaceType ty              `thenTc` \ ty' ->
188         -- It might not be of kind type
189     returnTc (Type ty')
190
191 tcCoreExpr (UfVar name)
192   = tcVar name  `thenTc` \ id ->
193     returnTc (Var id)
194
195 tcCoreExpr (UfLit lit)
196   = returnTc (Lit lit)
197
198 -- The dreaded lit-lits are also similar, except here the type
199 -- is read in explicitly rather than being implicit
200 tcCoreExpr (UfLitLit lit ty)
201   = tcIfaceType ty              `thenTc` \ ty' ->
202     returnTc (Lit (MachLitLit lit ty'))
203
204 tcCoreExpr (UfCCall cc ty)
205   = tcIfaceType ty      `thenTc` \ ty' ->
206     tcGetUnique         `thenNF_Tc` \ u ->
207     returnTc (Var (mkCCallOpId u cc ty'))
208
209 tcCoreExpr (UfTuple (HsTupCon _ boxity arity) args) 
210   = mapTc tcCoreExpr args       `thenTc` \ args' ->
211     let
212         -- Put the missing type arguments back in
213         con_args = map (Type . exprType) args' ++ args'
214     in
215     returnTc (mkApps (Var con_id) con_args)
216   where
217     con_id = dataConId (tupleCon boxity arity)
218     
219
220 tcCoreExpr (UfLam bndr body)
221   = tcCoreLamBndr bndr          $ \ bndr' ->
222     tcCoreExpr body             `thenTc` \ body' ->
223     returnTc (Lam bndr' body')
224
225 tcCoreExpr (UfApp fun arg)
226   = tcCoreExpr fun              `thenTc` \ fun' ->
227     tcCoreExpr arg              `thenTc` \ arg' ->
228     returnTc (App fun' arg')
229
230 tcCoreExpr (UfCase scrut case_bndr alts) 
231   = tcCoreExpr scrut                                    `thenTc` \ scrut' ->
232     let
233         scrut_ty = exprType scrut'
234         case_bndr' = mkVanillaId case_bndr scrut_ty
235     in
236     tcExtendGlobalValEnv [case_bndr']   $
237     mapTc (tcCoreAlt scrut_ty) alts     `thenTc` \ alts' ->
238     returnTc (Case scrut' case_bndr' alts')
239
240 tcCoreExpr (UfLet (UfNonRec bndr rhs) body)
241   = tcCoreExpr rhs              `thenTc` \ rhs' ->
242     tcCoreValBndr bndr          $ \ bndr' ->
243     tcCoreExpr body             `thenTc` \ body' ->
244     returnTc (Let (NonRec bndr' rhs') body')
245
246 tcCoreExpr (UfLet (UfRec pairs) body)
247   = tcCoreValBndrs bndrs        $ \ bndrs' ->
248     mapTc tcCoreExpr rhss       `thenTc` \ rhss' ->
249     tcCoreExpr body             `thenTc` \ body' ->
250     returnTc (Let (Rec (bndrs' `zip` rhss')) body')
251   where
252     (bndrs, rhss) = unzip pairs
253
254 tcCoreExpr (UfNote note expr) 
255   = tcCoreExpr expr             `thenTc` \ expr' ->
256     case note of
257         UfCoerce to_ty -> tcIfaceType to_ty     `thenTc` \ to_ty' ->
258                           returnTc (Note (Coerce to_ty'
259                                                  (exprType expr')) expr')
260         UfInlineCall   -> returnTc (Note InlineCall expr')
261         UfInlineMe     -> returnTc (Note InlineMe   expr')
262         UfSCC cc       -> returnTc (Note (SCC cc)   expr')
263 \end{code}
264
265 \begin{code}
266 tcCoreLamBndr (UfValBinder name ty) thing_inside
267   = tcIfaceType 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   = tcIfaceType 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 tcIfaceType 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     tcIfaceType 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@(con, names, rhs)
327   = tcConAlt con        `thenTc` \ con ->
328     let
329         (main_tyvars, _, ex_tyvars, _, _, _) = dataConSig con
330
331         (_, inst_tys, cons) = case splitAlgTyConApp_maybe scrut_ty of
332                                     Just stuff -> stuff
333                                     Nothing -> pprPanic "tcCoreAlt" (ppr alt)
334         ex_tyvars'          = [mkTyVar name (tyVarKind tv) | (name,tv) <- names `zip` ex_tyvars] 
335         ex_tys'             = mkTyVarTys ex_tyvars'
336         arg_tys             = dataConArgTys con (inst_tys ++ ex_tys')
337         id_names            = drop (length ex_tyvars) names
338         arg_ids
339 #ifdef DEBUG
340                 | length id_names /= length arg_tys
341                 = pprPanic "tcCoreAlts" (ppr (con, names, rhs) $$
342                                          (ppr main_tyvars <+> ppr ex_tyvars) $$
343                                          ppr arg_tys)
344                 | otherwise
345 #endif
346                 = zipWithEqual "tcCoreAlts" mkVanillaId id_names arg_tys
347     in
348     ASSERT( con `elem` cons && length inst_tys == length main_tyvars )
349     tcExtendTyVarEnv ex_tyvars'                 $
350     tcExtendGlobalValEnv arg_ids                $
351     tcCoreExpr rhs                                      `thenTc` \ rhs' ->
352     returnTc (DataAlt con, ex_tyvars' ++ arg_ids, rhs')
353
354
355 tcConAlt :: UfConAlt Name -> TcM DataCon
356 tcConAlt (UfTupleAlt (HsTupCon _ boxity arity))
357   = returnTc (tupleCon boxity arity)
358
359 tcConAlt (UfDataAlt con_name)
360   = tcVar con_name      `thenTc` \ con_id ->
361     returnTc (case isDataConWrapId_maybe con_id of
362                     Just con -> con
363                     Nothing  -> pprPanic "tcCoreAlt" (ppr con_id))
364 \end{code}
365
366 \begin{code}
367 ifaceSigCtxt sig_name
368   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
369 \end{code}
370