2b689acaa99248456750f86142fa883ed468cc9a
[ghc-hetmet.git] / ghc / compiler / typecheck / TcForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[TcForeign]{Typechecking \tr{foreign} declarations}
5
6 A foreign declaration is used to either give an externally
7 implemented function a Haskell type (and calling interface) or
8 give a Haskell function an external calling interface. Either way,
9 the range of argument and result types these functions can accommodate
10 is restricted to what the outside world understands (read C), and this
11 module checks to see if a foreign declaration has got a legal type.
12
13 \begin{code}
14 module TcForeign 
15         ( 
16           tcForeignImports
17         , tcForeignExports
18         ) where
19
20 #include "HsVersions.h"
21
22 import HsSyn            ( HsDecl(..), ForeignDecl(..), HsExpr(..),
23                           ExtName(..), isDynamic, MonoBinds(..),
24                           OutPat(..), ForKind(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcMonad
29 import TcEnv            ( tcLookupClassByKey, newLocalId, tcLookupGlobalValue )
30 import TcType           ( tcInstTcType, tcInstSigType, tcSplitRhoTy, zonkTcTypeToType )
31 import TcMonoType       ( tcHsType )
32 import TcHsSyn          ( TcMonoBinds, maybeBoxedPrimType, TypecheckedForeignDecl, TcIdOcc(..),
33                           TcForeignExportDecl )
34 import TcExpr           ( tcId, tcPolyExpr )                    
35 import Inst             ( emptyLIE, LIE, plusLIE )
36 import CoreSyn
37
38 import ErrUtils         ( Message )
39 import Id               ( Id, idName )
40 import Name             ( nameOccName )
41 import MkId             ( mkUserId )
42 import Type             ( isUnpointedType
43                         , splitFunTys
44                         , splitTyConApp_maybe
45                         , splitForAllTys
46                         , splitRhoTy
47                         , isForAllTy
48                         , mkForAllTys
49                         )
50 import TyVar            ( emptyTyVarEnv )
51
52
53 import TysWiredIn       ( isFFIArgumentTy, isFFIResultTy, 
54                           isFFIExternalTy, isAddrTy
55                         )
56 import Type             ( Type )
57 import Unique
58 import Unify            ( unifyTauTy )
59 import Outputable
60 import Util
61 import CmdLineOpts      ( opt_GlasgowExts )
62 import Maybes           ( maybeToBool )
63
64 \end{code}
65
66 \begin{code}
67 tcForeignImports :: [RenamedHsDecl] -> TcM s ([Id], [TypecheckedForeignDecl])
68 tcForeignImports decls = 
69    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
70
71 tcForeignExports :: [RenamedHsDecl] -> TcM s (LIE s, TcMonoBinds s, [TcForeignExportDecl s])
72 tcForeignExports decls = 
73    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
74                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
75   where
76    combine (lie, binds, fs) fe = 
77        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
78        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
79
80 -- defines a binding
81 isForeignImport :: ForeignDecl name -> Bool
82 isForeignImport (ForeignDecl _ k _ dyn _ _) =
83   case k of
84     FoImport _ -> True
85     FoExport   -> case dyn of { Dynamic -> True ; _ -> False }
86     FoLabel    -> True
87
88 -- exports a binding
89 isForeignExport :: ForeignDecl name -> Bool
90 isForeignExport (ForeignDecl _ FoExport _ ext_nm _ _) = not (isDynamic ext_nm)
91 isForeignExport _                                     = False
92
93 \end{code}
94
95 \begin{code}
96 tcFImport :: RenamedForeignDecl -> TcM s (Id, TypecheckedForeignDecl)
97 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
98    tcAddSrcLoc src_loc               $
99    tcAddErrCtxt (foreignDeclCtxt fo) $
100    tcHsType hs_ty                   `thenTc`    \ sig_ty ->
101    let
102       -- drop the foralls before inspecting the structure
103       -- of the foreign type.
104     (_, t_ty) = splitForAllTys sig_ty
105    in
106    case splitFunTys t_ty of
107      (arg_tys, res_ty) -> 
108         checkForeignExport True t_ty arg_tys res_ty `thenTc_`
109         let i = (mkUserId nm sig_ty) in
110         returnTc (i, (ForeignDecl i FoExport undefined Dynamic cconv src_loc))
111
112 tcFImport fo@(ForeignDecl nm FoLabel hs_ty ext_nm cconv src_loc) =
113    tcAddSrcLoc src_loc               $
114    tcAddErrCtxt (foreignDeclCtxt fo) $
115    tcHsType hs_ty                   `thenTc`    \ sig_ty ->
116    let
117       -- drop the foralls before inspecting the structure
118       -- of the foreign type.
119     (_, t_ty) = splitForAllTys sig_ty
120    in
121    check (isAddrTy t_ty) (illegalForeignTyErr False{-result-} sig_ty) `thenTc_`
122    let i = (mkUserId nm sig_ty) in
123    returnTc (i, (ForeignDecl i FoLabel undefined ext_nm cconv src_loc))
124
125 tcFImport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
126    tcAddSrcLoc src_loc               $
127    tcAddErrCtxt (foreignDeclCtxt fo) $
128
129    tcHsType hs_ty                    `thenTc` \ ty ->
130     -- Check that the type has the right shape
131     -- and that the argument and result types are acceptable.
132    let
133       -- drop the foralls before inspecting the structure
134       -- of the foreign type.
135     (_, t_ty) = splitForAllTys ty
136    in
137    case splitFunTys t_ty of
138      (arg_tys, res_ty) ->
139         checkForeignImport (isDynamic ext_nm) ty arg_tys res_ty `thenTc_`
140         let i = (mkUserId nm ty) in
141         returnTc (i, (ForeignDecl i imp_exp undefined ext_nm cconv src_loc))
142
143 tcFExport :: RenamedForeignDecl -> TcM s (LIE s, TcMonoBinds s, TcForeignExportDecl s)
144 tcFExport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
145    tcAddSrcLoc src_loc               $
146    tcAddErrCtxt (foreignDeclCtxt fo) $
147
148    tcHsType hs_ty                   `thenTc`    \ sig_ty ->
149    tcInstSigType sig_ty             `thenNF_Tc` \ sig_tc_ty ->
150    tcPolyExpr (HsVar nm) sig_tc_ty  `thenTc`    \ (rhs, lie, _, _, _) ->
151
152    let
153       -- drop the foralls before inspecting the structure
154       -- of the foreign type.
155     (_, t_ty) = splitForAllTys sig_ty
156    in
157    case splitFunTys t_ty of
158      (arg_tys, res_ty) -> 
159         checkForeignExport False t_ty arg_tys res_ty `thenTc_`
160           -- we're exporting a function, but at a type possibly more constrained
161           -- than its declared/inferred type. Hence the need
162           -- to create a local binding which will call the exported function
163           -- at a particular type (and, maybe, overloading).
164         newLocalId (nameOccName nm) sig_tc_ty   `thenNF_Tc` \ i ->
165         let
166             i2    = TcId i
167             bind  = VarMonoBind i2 rhs
168         in
169         returnTc (lie, bind, ForeignDecl i2 imp_exp undefined ext_nm cconv src_loc)
170         --                                          ^^^^^^^^^
171         -- ToDo: fill the type field in with something sensible.
172
173 \end{code}
174
175
176 \begin{code}
177 checkForeignImport :: Bool -> Type -> [Type] -> Type -> TcM s ()
178 checkForeignImport is_dynamic ty args res
179  | is_dynamic =
180     -- * first arg has got to be an Addr
181    case args of
182      []     -> check False (illegalForeignTyErr True{-Arg-} ty)
183      (x:xs) ->
184         check (isAddrTy x) (illegalForeignTyErr True{-Arg-} ty) `thenTc_`
185         mapTc (checkForeignArg isFFIArgumentTy) xs              `thenTc_`
186         checkForeignRes (isFFIResultTy) res
187  | otherwise =
188      mapTc (checkForeignArg isFFIArgumentTy) args               `thenTc_`
189      checkForeignRes (isFFIResultTy) res
190
191 checkForeignExport :: Bool -> Type -> [Type] -> Type -> TcM s ()
192 checkForeignExport is_dynamic ty args res
193  | is_dynamic = 
194     -- * the first (and only!) arg has got to be a function type
195     -- * result type is an Addr
196    case args of
197      [arg]  ->
198         case splitFunTys arg of
199            (arg_tys, res_ty) -> 
200                 mapTc (checkForeignArg isFFIExternalTy) arg_tys `thenTc_`
201                 checkForeignRes (isFFIResultTy) res_ty          `thenTc_`
202                 checkForeignRes (isAddrTy) res
203      _      -> check False (illegalForeignTyErr True{-Arg-} ty)
204  | otherwise =
205      mapTc (checkForeignArg isFFIExternalTy) args               `thenTc_`
206      checkForeignRes (isFFIResultTy) res
207  
208 check :: Bool -> Message -> TcM s ()
209 check True _       = returnTc ()
210 check _    the_err = addErrTc the_err `thenNF_Tc_` returnTc ()
211
212 checkForeignArg :: (Type -> Bool) -> Type -> TcM s ()
213 checkForeignArg pred ty = check (pred ty) (illegalForeignTyErr True{-Arg-} ty)
214
215 -- Check that the type has the form 
216 --    (IO t) and that t satisfies the given predicate.
217 --
218 checkForeignRes :: (Type -> Bool) -> Type -> TcM s ()
219 checkForeignRes pred_res_ty ty =
220  case (splitTyConApp_maybe ty) of
221     Just (io, [res_ty]) 
222         | (uniqueOf io) == ioTyConKey &&
223           pred_res_ty res_ty 
224         -> returnTc ()
225     _   | pred_res_ty ty -> returnTc ()
226         | otherwise      -> check False (illegalForeignTyErr False{-Res-} ty)
227
228 \end{code}
229
230 Warnings
231
232 \begin{code}
233 illegalForeignTyErr isArg ty
234   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration")])
235          4 (hsep [ ptext SLIT("type:"),  ppr ty])
236   where
237    arg_or_res
238     | isArg     = ptext SLIT("argument")
239     | otherwise = ptext SLIT("result")
240
241 foreignDeclCtxt fo = 
242  hang (ptext SLIT("When checking a foreign declaration:"))
243   4   (ppr fo)
244
245 \end{code}