6c51aee7c2514e9cf84891c0076403f7f9c80fdb
[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(Dynamic), isDynamicExtName, MonoBinds(..),
24                           ForKind(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcMonad
29 import TcEnv            ( newLocalId )
30 import TcMonoType       ( tcHsBoxedSigType )
31 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl,
32                           TcForeignExportDecl )
33 import TcExpr           ( tcPolyExpr )                  
34 import Inst             ( emptyLIE, LIE, plusLIE )
35
36 import ErrUtils         ( Message )
37 import Id               ( Id, mkVanillaId )
38 import Name             ( nameOccName )
39 import Type             ( splitFunTys
40                         , splitTyConApp_maybe
41                         , splitForAllTys
42                         )
43 import TysWiredIn       ( isFFIArgumentTy, isFFIResultTy, 
44                           isFFIExternalTy, isFFIDynArgumentTy, isFFIDynResultTy,
45                           isFFILabelTy
46                         )
47 import Type             ( Type )
48 import PrelNames        ( hasKey, ioTyConKey )
49 import Outputable
50
51 \end{code}
52
53 \begin{code}
54 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
55 tcForeignImports decls = 
56    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
57
58 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
59 tcForeignExports decls = 
60    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
61                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
62   where
63    combine (lie, binds, fs) fe = 
64        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
65        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
66
67 -- defines a binding
68 isForeignImport :: ForeignDecl name -> Bool
69 isForeignImport (ForeignDecl _ k _ dyn _ _) =
70   case k of
71     FoImport _ -> True
72     FoExport   -> case dyn of { Dynamic -> True ; _ -> False }
73     FoLabel    -> True
74
75 -- exports a binding
76 isForeignExport :: ForeignDecl name -> Bool
77 isForeignExport (ForeignDecl _ FoExport _ ext_nm _ _) = not (isDynamicExtName ext_nm)
78 isForeignExport _                                     = False
79
80 \end{code}
81
82 \begin{code}
83 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
84 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
85    tcAddSrcLoc src_loc               $
86    tcAddErrCtxt (foreignDeclCtxt fo) $
87    tcHsBoxedSigType hs_ty            `thenTc`   \ sig_ty ->
88    let
89       -- drop the foralls before inspecting the structure
90       -- of the foreign type.
91     (_, t_ty) = splitForAllTys sig_ty
92    in
93    case splitFunTys t_ty of
94      (arg_tys, res_ty) -> 
95         checkForeignExport True t_ty arg_tys res_ty `thenTc_`
96         let i = (mkVanillaId nm sig_ty) in
97         returnTc (i, (ForeignDecl i FoExport undefined Dynamic cconv src_loc))
98
99 tcFImport fo@(ForeignDecl nm FoLabel hs_ty ext_nm cconv src_loc) =
100    tcAddSrcLoc src_loc               $
101    tcAddErrCtxt (foreignDeclCtxt fo) $
102    tcHsBoxedSigType hs_ty           `thenTc`    \ sig_ty ->
103    let
104       -- drop the foralls before inspecting the structure
105       -- of the foreign type.
106     (_, t_ty) = splitForAllTys sig_ty
107    in
108    check (isFFILabelTy t_ty) 
109         (illegalForeignTyErr False{-result-} sig_ty)    `thenTc_`
110    let i = (mkVanillaId nm sig_ty) in
111    returnTc (i, (ForeignDecl i FoLabel undefined ext_nm cconv src_loc))
112
113 tcFImport fo@(ForeignDecl nm imp_exp@(FoImport isUnsafe) hs_ty ext_nm cconv src_loc) =
114    tcAddSrcLoc src_loc               $
115    tcAddErrCtxt (foreignDeclCtxt fo) $
116
117    tcHsBoxedSigType hs_ty                    `thenTc` \ ty ->
118     -- Check that the type has the right shape
119     -- and that the argument and result types are acceptable.
120    let
121       -- drop the foralls before inspecting the structure
122       -- of the foreign type.
123     (_, t_ty) = splitForAllTys ty
124    in
125    case splitFunTys t_ty of
126      (arg_tys, res_ty) ->
127         checkForeignImport (isDynamicExtName ext_nm) (not isUnsafe) ty arg_tys res_ty `thenTc_`
128         let i = (mkVanillaId nm ty) in
129         returnTc (i, (ForeignDecl i imp_exp undefined ext_nm cconv src_loc))
130
131 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
132 tcFExport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
133    tcAddSrcLoc src_loc               $
134    tcAddErrCtxt (foreignDeclCtxt fo) $
135
136    tcHsBoxedSigType hs_ty              `thenTc` \ sig_ty ->
137    tcPolyExpr (HsVar nm) sig_ty     `thenTc`    \ (rhs, lie, _, _, _) ->
138
139    let
140       -- drop the foralls before inspecting the structure
141       -- of the foreign type.
142     (_, t_ty) = splitForAllTys sig_ty
143    in
144    case splitFunTys t_ty of
145      (arg_tys, res_ty) -> 
146         checkForeignExport False t_ty arg_tys res_ty `thenTc_`
147           -- we're exporting a function, but at a type possibly more constrained
148           -- than its declared/inferred type. Hence the need
149           -- to create a local binding which will call the exported function
150           -- at a particular type (and, maybe, overloading).
151         newLocalId (nameOccName nm) sig_ty src_loc      `thenNF_Tc` \ i ->
152         let
153             bind  = VarMonoBind i rhs
154         in
155         returnTc (lie, bind, ForeignDecl i imp_exp undefined ext_nm cconv src_loc)
156         --                                          ^^^^^^^^^
157         -- ToDo: fill the type field in with something sensible.
158
159 \end{code}
160
161
162 \begin{code}
163 checkForeignImport :: Bool -> Bool -> Type -> [Type] -> Type -> TcM ()
164 checkForeignImport is_dynamic is_safe ty args res
165  | is_dynamic =
166     -- * first arg has got to be an Addr
167    case args of
168      []     -> check False (illegalForeignTyErr True{-Arg-} ty)
169      (x:xs) ->
170         check (isFFIDynArgumentTy x) (illegalForeignTyErr True{-Arg-} ty) `thenTc_`
171         mapTc (checkForeignArg (isFFIArgumentTy is_safe)) xs    `thenTc_`
172         checkForeignRes True {-NonIO ok-} isFFIResultTy res
173  | otherwise =
174      mapTc (checkForeignArg (isFFIArgumentTy is_safe)) args     `thenTc_`
175      checkForeignRes True {-NonIO ok-} isFFIResultTy res
176
177 checkForeignExport :: Bool -> Type -> [Type] -> Type -> TcM ()
178 checkForeignExport is_dynamic ty args res
179  | is_dynamic = 
180     -- * the first (and only!) arg has got to be a function type
181     --   and it must return IO t
182     -- * result type is IO Addr
183    case args of
184      [arg]  ->
185         case splitFunTys arg of
186            (arg_tys, res_ty) -> 
187                 mapTc (checkForeignArg isFFIExternalTy) arg_tys `thenTc_`
188                 checkForeignRes True {-NonIO ok-} isFFIResultTy res_ty `thenTc_`
189                 checkForeignRes False {-Must be IO-} isFFIDynResultTy res
190      _      -> check False (illegalForeignTyErr True{-Arg-} ty)
191  | otherwise =
192      mapTc (checkForeignArg isFFIExternalTy) args               `thenTc_`
193      checkForeignRes True {-NonIO ok-} isFFIResultTy res
194  
195 checkForeignArg :: (Type -> Bool) -> Type -> TcM ()
196 checkForeignArg pred ty = check (pred ty) (illegalForeignTyErr True{-Arg-} ty)
197
198 -- Check that the type has the form 
199 --    (IO t) or (t) , and that t satisfies the given predicate.
200 --
201 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
202 checkForeignRes non_io_result_ok pred_res_ty ty =
203  case (splitTyConApp_maybe ty) of
204     Just (io, [res_ty]) 
205         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
206         -> returnTc ()
207     _   
208         -> check (non_io_result_ok && pred_res_ty ty) 
209                  (illegalForeignTyErr False{-Res-} ty)
210 \end{code}
211
212 Warnings
213
214 \begin{code}
215 check :: Bool -> Message -> TcM ()
216 check True _       = returnTc ()
217 check _    the_err = addErrTc the_err `thenNF_Tc_` returnTc ()
218
219 illegalForeignTyErr isArg ty
220   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
221          4 (hsep [ppr ty])
222   where
223    arg_or_res
224     | isArg     = ptext SLIT("argument")
225     | otherwise = ptext SLIT("result")
226
227 foreignDeclCtxt fo = 
228  hang (ptext SLIT("When checking declaration:"))
229   4   (ppr fo)
230 \end{code}