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