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