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