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