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