[project @ 2000-07-11 16:24:57 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           ( typeToTcType, tcSplitRhoTy, zonkTcTypeToType )
31 import TcMonoType       ( tcHsTopBoxedType )
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                         )
47 import Type             ( Type )
48 import Unique
49 import Outputable
50
51 \end{code}
52
53 \begin{code}
54 tcForeignImports :: [RenamedHsDecl] -> TcM s ([Id], [TypecheckedForeignDecl])
55 tcForeignImports decls = 
56    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
57
58 tcForeignExports :: [RenamedHsDecl] -> TcM s (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 s (Id, TypecheckedForeignDecl)
84 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
85    tcAddSrcLoc src_loc               $
86    tcAddErrCtxt (foreignDeclCtxt fo) $
87    tcHsTopBoxedType 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    tcHsTopBoxedType 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 (isAddrTy t_ty) (illegalForeignTyErr False{-result-} sig_ty) `thenTc_`
109    let i = (mkVanillaId nm sig_ty) in
110    returnTc (i, (ForeignDecl i FoLabel undefined ext_nm cconv src_loc))
111
112 tcFImport fo@(ForeignDecl nm imp_exp@(FoImport isUnsafe) hs_ty ext_nm cconv src_loc) =
113    tcAddSrcLoc src_loc               $
114    tcAddErrCtxt (foreignDeclCtxt fo) $
115
116    tcHsTopBoxedType hs_ty            `thenTc` \ ty ->
117     -- Check that the type has the right shape
118     -- and that the argument and result types are acceptable.
119    let
120       -- drop the foralls before inspecting the structure
121       -- of the foreign type.
122     (_, t_ty) = splitForAllTys ty
123    in
124    case splitFunTys t_ty of
125      (arg_tys, res_ty) ->
126         checkForeignImport (isDynamicExtName ext_nm) (not isUnsafe) ty arg_tys res_ty `thenTc_`
127         let i = (mkVanillaId nm ty) in
128         returnTc (i, (ForeignDecl i imp_exp undefined ext_nm cconv src_loc))
129
130 tcFExport :: RenamedForeignDecl -> TcM s (LIE, TcMonoBinds, TcForeignExportDecl)
131 tcFExport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
132    tcAddSrcLoc src_loc               $
133    tcAddErrCtxt (foreignDeclCtxt fo) $
134
135    tcHsTopBoxedType hs_ty              `thenTc` \ sig_ty ->
136    let sig_tc_ty = typeToTcType sig_ty in
137    tcPolyExpr (HsVar nm) sig_tc_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_tc_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 s ()
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 (isAddrTy 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 s ()
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 an Addr or 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-} isAddrTy      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 s ()
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 s ()
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 s ()
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}