[project @ 2000-07-26 13:13:49 by simonmar]
[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                           OutPat(..), ForKind(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcMonad
29 import TcEnv            ( newLocalId )
30 import TcType           ( tcSplitRhoTy, zonkTcTypeToType )
31 import TcMonoType       ( tcHsBoxedSigType )
32 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl,
33                           TcForeignExportDecl )
34 import TcExpr           ( tcId, tcPolyExpr )                    
35 import Inst             ( emptyLIE, LIE, plusLIE )
36
37 import ErrUtils         ( Message )
38 import Id               ( Id, idName, mkVanillaId )
39 import Name             ( nameOccName )
40 import Type             ( splitFunTys
41                         , splitTyConApp_maybe
42                         , splitForAllTys
43                         )
44 import TysWiredIn       ( isFFIArgumentTy, isFFIResultTy, 
45                           isFFIExternalTy, isAddrTy,
46                           isFFIDynResultTy, isFFILabelTy
47                         )
48 import Type             ( Type )
49 import Unique
50 import Outputable
51
52 \end{code}
53
54 \begin{code}
55 tcForeignImports :: [RenamedHsDecl] -> TcM s ([Id], [TypecheckedForeignDecl])
56 tcForeignImports decls = 
57    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
58
59 tcForeignExports :: [RenamedHsDecl] -> TcM s (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 s (Id, TypecheckedForeignDecl)
85 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
86    tcAddSrcLoc src_loc               $
87    tcAddErrCtxt (foreignDeclCtxt fo) $
88    tcHsBoxedSigType 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    tcHsBoxedSigType 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    tcHsBoxedSigType 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 s (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    tcHsBoxedSigType 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 s ()
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         check (isAddrTy x) (illegalForeignTyErr True{-Arg-} ty) `thenTc_`
172         mapTc (checkForeignArg (isFFIArgumentTy is_safe)) xs    `thenTc_`
173         checkForeignRes True {-NonIO ok-} isFFIResultTy res
174  | otherwise =
175      mapTc (checkForeignArg (isFFIArgumentTy is_safe)) args     `thenTc_`
176      checkForeignRes True {-NonIO ok-} isFFIResultTy res
177
178 checkForeignExport :: Bool -> Type -> [Type] -> Type -> TcM s ()
179 checkForeignExport is_dynamic ty args res
180  | is_dynamic = 
181     -- * the first (and only!) arg has got to be a function type
182     --   and it must return IO t
183     -- * result type is an Addr or IO Addr
184    case args of
185      [arg]  ->
186         case splitFunTys arg of
187            (arg_tys, res_ty) -> 
188                 mapTc (checkForeignArg isFFIExternalTy) arg_tys `thenTc_`
189                 checkForeignRes True {-NonIO ok-} isFFIResultTy res_ty `thenTc_`
190                 checkForeignRes False {-Must be IO-} isFFIDynResultTy res
191      _      -> check False (illegalForeignTyErr True{-Arg-} ty)
192  | otherwise =
193      mapTc (checkForeignArg isFFIExternalTy) args               `thenTc_`
194      checkForeignRes True {-NonIO ok-} isFFIResultTy res
195  
196 checkForeignArg :: (Type -> Bool) -> Type -> TcM s ()
197 checkForeignArg pred ty = check (pred ty) (illegalForeignTyErr True{-Arg-} ty)
198
199 -- Check that the type has the form 
200 --    (IO t) or (t) , and that t satisfies the given predicate.
201 --
202 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM s ()
203 checkForeignRes non_io_result_ok pred_res_ty ty =
204  case (splitTyConApp_maybe ty) of
205     Just (io, [res_ty]) 
206         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
207         -> returnTc ()
208     _   
209         -> check (non_io_result_ok && pred_res_ty ty) 
210                  (illegalForeignTyErr False{-Res-} ty)
211 \end{code}
212
213 Warnings
214
215 \begin{code}
216 check :: Bool -> Message -> TcM s ()
217 check True _       = returnTc ()
218 check _    the_err = addErrTc the_err `thenNF_Tc_` returnTc ()
219
220 illegalForeignTyErr isArg ty
221   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
222          4 (hsep [ppr ty])
223   where
224    arg_or_res
225     | isArg     = ptext SLIT("argument")
226     | otherwise = ptext SLIT("result")
227
228 foreignDeclCtxt fo = 
229  hang (ptext SLIT("When checking declaration:"))
230   4   (ppr fo)
231 \end{code}