[project @ 1998-03-19 23:54:49 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcIfaceSig.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcIfaceSig]{Type checking of type signatures in interface files}
5
6 \begin{code}
7 module TcIfaceSig ( tcInterfaceSigs ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( HsDecl(..), IfaceSig(..) )
12 import TcMonad
13 import TcMonoType       ( tcHsType, tcHsTypeKind, tcTyVarScope )
14 import TcEnv            ( tcExtendTyVarEnv, tcExtendGlobalValEnv,
15                           tcLookupTyConByKey, tcLookupGlobalValueMaybe,
16                           tcExplicitLookupGlobal
17                         )
18 import TcKind           ( TcKind, kindToTcKind )
19
20 import RnHsSyn          ( RenamedHsDecl(..) )
21 import HsCore
22 import HsDecls          ( HsIdInfo(..), HsStrictnessInfo(..) )
23 import Literal          ( Literal(..) )
24 import CoreSyn
25 import CoreUtils        ( coreExprType )
26 import CoreUnfold
27 import MagicUFs         ( MagicUnfoldingFun )
28 import WwLib            ( mkWrapper )
29 import PrimOp           ( PrimOp(..) )
30
31 import MkId             ( mkImportedId, mkUserId )
32 import Id               ( Id, addInlinePragma, isPrimitiveId_maybe, dataConArgTys )
33 import IdInfo
34 import SpecEnv          ( addToSpecEnv )
35 import Type             ( mkSynTy, splitAlgTyConApp )
36 import TyVar            ( mkSysTyVar )
37 import Name             ( Name )
38 import Unique           ( rationalTyConKey, uniqueOf )
39 import TysWiredIn       ( integerTy )
40 import ErrUtils         ( pprBagOfErrors )
41 import Maybes           ( maybeToBool, MaybeErr(..) )
42 import Outputable       
43 import Util             ( zipWithEqual )
44
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 :: TcEnv s              -- Envt to use when checking unfoldings
56                 -> [RenamedHsDecl]      -- Ignore non-sig-decls in these decls
57                 -> TcM s [Id]
58                 
59
60 tcInterfaceSigs unf_env (SigD (IfaceSig name ty id_infos src_loc) : rest)
61   = tcAddSrcLoc src_loc (
62     tcAddErrCtxt (ifaceSigCtxt name) (
63         tcHsType ty                                             `thenTc` \ sigma_ty ->
64         tcIdInfo unf_env name sigma_ty noIdInfo id_infos        `thenTc` \ id_info ->
65         returnTc (mkImportedId name sigma_ty id_info)
66     ))                                          `thenTc` \ sig_id ->
67     tcInterfaceSigs unf_env rest                `thenTc` \ sig_ids ->
68     returnTc (sig_id : sig_ids)
69
70 tcInterfaceSigs unf_env (other_decl : rest) = tcInterfaceSigs unf_env rest
71
72 tcInterfaceSigs unf_env [] = returnTc []
73 \end{code}
74
75 \begin{code}
76 tcIdInfo unf_env name ty info info_ins
77   = foldlTc tcPrag noIdInfo info_ins
78   where
79     tcPrag info (HsArity arity) = returnTc (arity `setArityInfo` info)
80     tcPrag info (HsUpdate upd)  = returnTc (upd   `setUpdateInfo` info)
81     tcPrag info (HsFBType fb)   = returnTc (fb    `setFBTypeInfo` info)
82     tcPrag info (HsArgUsage au) = returnTc (au    `setArgUsageInfo` info)
83
84     tcPrag info (HsUnfold inline expr)
85         = tcPragExpr unf_env name expr  `thenNF_Tc` \ maybe_expr' ->
86           let
87                 -- maybe_expr doesn't get looked at if the unfolding
88                 -- is never inspected; so the typecheck doesn't even happen
89                 unfold_info = case maybe_expr' of
90                                 Nothing    -> NoUnfolding
91                                 Just expr' -> mkUnfolding expr' 
92                 info1 = unfold_info `setUnfoldingInfo` info
93
94                 info2 | inline    = IWantToBeINLINEd `setInlinePragInfo` info1
95                       | otherwise = info1
96           in
97           returnTc info2
98
99     tcPrag info (HsStrictness strict)
100         = tcStrictness unf_env ty info strict
101
102     tcPrag info (HsSpecialise tyvars tys rhs)
103         = tcTyVarScope tyvars           $ \ tyvars' ->
104           mapTc tcHsType tys            `thenTc` \ tys' -> 
105           tcPragExpr unf_env name rhs   `thenNF_Tc` \ maybe_rhs' ->
106           let
107                 -- If spec_env isn't looked at, none of this 
108                 -- actually takes place
109             spec_env  = specInfo info
110             spec_env' = case maybe_rhs' of
111                           Nothing -> spec_env
112                           Just rhs' -> case addToSpecEnv True {- overlap ok -} spec_env tyvars' tys' rhs' of
113                                           Succeeded spec_env' -> spec_env'
114                                           Failed err          -> pprTrace "tcIdInfo: bad specialisation"
115                                                                           (ppr name <+> ppr err) $
116                                                                  spec_env
117           in
118           returnTc (spec_env' `setSpecInfo` info)
119 \end{code}
120
121 \begin{code}
122 tcStrictness unf_env ty info (HsStrictnessInfo demands maybe_worker)
123   = tcWorker unf_env maybe_worker               `thenNF_Tc` \ maybe_worker_id ->
124     uniqSMToTcM (mkWrapper ty demands)          `thenNF_Tc` \ wrap_fn ->
125     let
126         -- Watch out! We can't pull on maybe_worker_id too eagerly!
127         info' = case maybe_worker_id of
128                         Just worker_id -> setUnfoldingInfo (mkUnfolding (wrap_fn worker_id)) $
129                                           setInlinePragInfo IWantToBeINLINEd info
130
131                         Nothing        -> info
132
133         has_worker = maybeToBool maybe_worker_id
134     in
135     returnTc (StrictnessInfo demands has_worker  `setStrictnessInfo` info')
136
137 -- Boring to write these out, but the result type differs from the arg type...
138 tcStrictness unf_env ty info HsBottom
139   = returnTc (BottomGuaranteed `setStrictnessInfo` info)
140 \end{code}
141
142 \begin{code}
143 tcWorker unf_env Nothing = returnNF_Tc Nothing
144
145 tcWorker unf_env (Just (worker_name,_))
146   = returnNF_Tc (trace_maybe maybe_worker_id)
147   where
148     maybe_worker_id = tcExplicitLookupGlobal unf_env worker_name
149
150         -- The trace is so we can see what's getting dropped
151     trace_maybe Nothing  = pprTrace "tcWorker failed:" (ppr worker_name) Nothing
152     trace_maybe (Just x) = Just x
153 \end{code}
154
155 For unfoldings we try to do the job lazily, so that we never type check
156 an unfolding that isn't going to be looked at.
157
158 \begin{code}
159 tcPragExpr unf_env name core_expr
160   = forkNF_Tc (
161         recoverNF_Tc no_unfolding (
162                 tcSetEnv unf_env $
163                 tcCoreExpr core_expr    `thenTc` \ core_expr' ->
164                 returnTc (Just core_expr')
165     ))                  
166   where
167         -- The trace tells what wasn't available, for the benefit of
168         -- compiler hackers who want to improve it!
169     no_unfolding = getErrsTc            `thenNF_Tc` \ (warns,errs) ->
170                    returnNF_Tc (pprTrace "tcUnfolding failed with:" 
171                                          (hang (ppr name) 4 (pprBagOfErrors errs))
172                                          Nothing)
173 \end{code}
174
175
176 Variables in unfoldings
177 ~~~~~~~~~~~~~~~~~~~~~~~
178 ****** Inside here we use only the Global environment, even for locally bound variables.
179 ****** Why? Because we know all the types and want to bind them to real Ids.
180
181 \begin{code}
182 tcVar :: Name -> TcM s Id
183 tcVar name
184   = tcLookupGlobalValueMaybe name       `thenNF_Tc` \ maybe_id ->
185     case maybe_id of {
186         Just id -> returnTc id;
187         Nothing -> failWithTc (noDecl name)
188     }
189
190 noDecl name = hsep [ptext SLIT("Warning: no binding for"), ppr name]
191 \end{code}
192
193 UfCore expressions.
194
195 \begin{code}
196 tcCoreExpr :: UfExpr Name -> TcM s CoreExpr
197
198 tcCoreExpr (UfVar name)
199   = tcVar name  `thenTc` \ id ->
200     returnTc (Var id)
201
202 -- rationalTy isn't built in so we have to construct it
203 -- (the "ty" part of the incoming literal is simply bottom)
204 tcCoreExpr (UfLit (NoRepRational lit _)) 
205   = tcLookupTyConByKey rationalTyConKey `thenNF_Tc` \ rational_tycon ->
206     let
207         rational_ty  = mkSynTy rational_tycon []
208     in
209     returnTc (Lit (NoRepRational lit rational_ty)) 
210
211 -- Similarly for integers, except that it is wired in
212 tcCoreExpr (UfLit (NoRepInteger lit _)) 
213   = returnTc (Lit (NoRepInteger lit integerTy))
214
215 tcCoreExpr (UfLit other_lit)
216   = returnTc (Lit other_lit)
217
218 tcCoreExpr (UfCon con args) 
219   = tcVar con                   `thenTc` \ con_id ->
220     mapTc tcCoreArg args        `thenTc` \ args' ->
221     returnTc (Con con_id args')
222
223 tcCoreExpr (UfPrim prim args) 
224   = tcCorePrim prim             `thenTc` \ primop ->
225     mapTc tcCoreArg args        `thenTc` \ args' ->
226     returnTc (Prim primop args')
227
228 tcCoreExpr (UfApp fun arg)
229   = tcCoreExpr fun              `thenTc` \ fun' ->
230     tcCoreArg arg               `thenTc` \ arg' ->
231     returnTc (App fun' arg')
232
233 tcCoreExpr (UfCase scrut alts) 
234   = tcCoreExpr scrut                            `thenTc` \ scrut' ->
235     tcCoreAlts (coreExprType scrut') alts       `thenTc` \ alts' ->
236     returnTc (Case scrut' alts')
237
238 tcCoreExpr (UfNote note expr) 
239   = tcCoreExpr expr             `thenTc` \ expr' ->
240     case note of
241         UfCoerce to_ty -> tcHsTypeKind to_ty    `thenTc` \ (_,to_ty') ->
242                           returnTc (Note (Coerce to_ty' (coreExprType expr')) expr')
243         UfInlineCall   -> returnTc (Note InlineCall expr')
244         UfSCC cc       -> returnTc (Note (SCC cc) expr')
245
246 tcCoreNote (UfSCC cc)   = returnTc (SCC cc)
247 tcCoreNote UfInlineCall = returnTc InlineCall 
248 \end{code}
249     returnTc (Note note' expr') 
250
251 tcCoreExpr (UfLam bndr body)
252   = tcCoreLamBndr bndr          $ \ bndr' ->
253     tcCoreExpr body             `thenTc` \ body' ->
254     returnTc (Lam bndr' body')
255
256 tcCoreExpr (UfLet (UfNonRec bndr rhs) body)
257   = tcCoreExpr rhs              `thenTc` \ rhs' ->
258     tcCoreValBndr bndr          $ \ bndr' ->
259     tcCoreExpr body             `thenTc` \ body' ->
260     returnTc (Let (NonRec bndr' rhs') body')
261
262 tcCoreExpr (UfLet (UfRec pairs) body)
263   = tcCoreValBndrs bndrs        $ \ bndrs' ->
264     mapTc tcCoreExpr rhss       `thenTc` \ rhss' ->
265     tcCoreExpr body             `thenTc` \ body' ->
266     returnTc (Let (Rec (bndrs' `zip` rhss')) body')
267   where
268     (bndrs, rhss) = unzip pairs
269 \end{code}
270
271 \begin{code}
272 tcCoreLamBndr (UfValBinder name ty) thing_inside
273   = tcHsType ty                 `thenTc` \ ty' ->
274     let
275         id = mkUserId name ty'
276     in
277     tcExtendGlobalValEnv [id] $
278     thing_inside (ValBinder id)
279     
280 tcCoreLamBndr (UfTyBinder name kind) thing_inside
281   = let
282         tyvar = mkSysTyVar (uniqueOf name) kind
283     in
284     tcExtendTyVarEnv [name] [(kindToTcKind kind, tyvar)] $
285     thing_inside (TyBinder tyvar)
286     
287 tcCoreValBndr (UfValBinder name ty) thing_inside
288   = tcHsType ty                 `thenTc` \ ty' ->
289     let
290         id = mkUserId name ty'
291     in
292     tcExtendGlobalValEnv [id] $
293     thing_inside id
294     
295 tcCoreValBndrs bndrs thing_inside               -- Expect them all to be ValBinders
296   = mapTc tcHsType tys                  `thenTc` \ tys' ->
297     let
298         ids = zipWithEqual "tcCoreValBndr" mkUserId names tys'
299     in
300     tcExtendGlobalValEnv ids $
301     thing_inside ids
302   where
303     names = map (\ (UfValBinder name _) -> name) bndrs
304     tys   = map (\ (UfValBinder _   ty) -> ty)   bndrs
305 \end{code}    
306
307 \begin{code}
308 tcCoreArg (UfVarArg v)   = tcVar v              `thenTc` \ v' -> returnTc (VarArg v')
309 tcCoreArg (UfTyArg ty)   = tcHsTypeKind ty      `thenTc` \ (_,ty') -> returnTc (TyArg ty')
310 tcCoreArg (UfLitArg lit) = returnTc (LitArg lit)
311
312 tcCoreAlts scrut_ty (UfAlgAlts alts deflt)
313   = mapTc tc_alt alts                   `thenTc` \ alts' ->
314     tcCoreDefault scrut_ty deflt        `thenTc` \ deflt' ->
315     returnTc (AlgAlts alts' deflt')
316   where
317     tc_alt (con, names, rhs)
318       = tcVar con                       `thenTc` \ con' ->
319         let
320             arg_tys                 = dataConArgTys con' inst_tys
321             (tycon, inst_tys, cons) = splitAlgTyConApp scrut_ty
322             arg_ids                 = zipWithEqual "tcCoreAlts" mkUserId names arg_tys
323         in
324         tcExtendGlobalValEnv arg_ids    $
325         tcCoreExpr rhs                  `thenTc` \ rhs' ->
326         returnTc (con', arg_ids, rhs')
327
328 tcCoreAlts scrut_ty (UfPrimAlts alts deflt)
329   = mapTc tc_alt alts                   `thenTc` \ alts' ->
330     tcCoreDefault scrut_ty deflt        `thenTc` \ deflt' ->
331     returnTc (PrimAlts alts' deflt')
332   where
333     tc_alt (lit, rhs) = tcCoreExpr rhs          `thenTc` \ rhs' ->
334                         returnTc (lit, rhs')
335
336 tcCoreDefault scrut_ty UfNoDefault = returnTc NoDefault
337 tcCoreDefault scrut_ty (UfBindDefault name rhs)
338   = let
339         deflt_id = mkUserId name scrut_ty
340     in
341     tcExtendGlobalValEnv [deflt_id]     $
342     tcCoreExpr rhs                      `thenTc` \ rhs' ->
343     returnTc (BindDefault deflt_id rhs')
344     
345
346 tcCorePrim (UfOtherOp op) 
347   = tcVar op            `thenTc` \ op_id ->
348     case isPrimitiveId_maybe op_id of
349         Just prim_op -> returnTc prim_op
350         Nothing      -> pprPanic "tcCorePrim" (ppr op_id)
351
352 tcCorePrim (UfCCallOp str casm gc arg_tys res_ty)
353   = mapTc tcHsType arg_tys      `thenTc` \ arg_tys' ->
354     tcHsType res_ty             `thenTc` \ res_ty' ->
355     returnTc (CCallOp str casm gc arg_tys' res_ty')
356 \end{code}
357
358 \begin{code}
359 ifaceSigCtxt sig_name
360   = hsep [ptext SLIT("In an interface-file signature for"), ppr sig_name]
361 \end{code}
362