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