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