[project @ 2000-07-14 08:17:36 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                           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                         )
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    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 (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    tcHsBoxedSigType 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    tcHsBoxedSigType hs_ty              `thenTc` \ sig_ty ->
136    tcPolyExpr (HsVar nm) sig_ty     `thenTc`    \ (rhs, lie, _, _, _) ->
137
138    let
139       -- drop the foralls before inspecting the structure
140       -- of the foreign type.
141     (_, t_ty) = splitForAllTys sig_ty
142    in
143    case splitFunTys t_ty of
144      (arg_tys, res_ty) -> 
145         checkForeignExport False t_ty arg_tys res_ty `thenTc_`
146           -- we're exporting a function, but at a type possibly more constrained
147           -- than its declared/inferred type. Hence the need
148           -- to create a local binding which will call the exported function
149           -- at a particular type (and, maybe, overloading).
150         newLocalId (nameOccName nm) sig_ty src_loc      `thenNF_Tc` \ i ->
151         let
152             bind  = VarMonoBind i rhs
153         in
154         returnTc (lie, bind, ForeignDecl i imp_exp undefined ext_nm cconv src_loc)
155         --                                          ^^^^^^^^^
156         -- ToDo: fill the type field in with something sensible.
157
158 \end{code}
159
160
161 \begin{code}
162 checkForeignImport :: Bool -> Bool -> Type -> [Type] -> Type -> TcM s ()
163 checkForeignImport is_dynamic is_safe ty args res
164  | is_dynamic =
165     -- * first arg has got to be an Addr
166    case args of
167      []     -> check False (illegalForeignTyErr True{-Arg-} ty)
168      (x:xs) ->
169         check (isAddrTy x) (illegalForeignTyErr True{-Arg-} ty) `thenTc_`
170         mapTc (checkForeignArg (isFFIArgumentTy is_safe)) xs    `thenTc_`
171         checkForeignRes True {-NonIO ok-} isFFIResultTy res
172  | otherwise =
173      mapTc (checkForeignArg (isFFIArgumentTy is_safe)) args     `thenTc_`
174      checkForeignRes True {-NonIO ok-} isFFIResultTy res
175
176 checkForeignExport :: Bool -> Type -> [Type] -> Type -> TcM s ()
177 checkForeignExport is_dynamic ty args res
178  | is_dynamic = 
179     -- * the first (and only!) arg has got to be a function type
180     --   and it must return IO t
181     -- * result type is an Addr or IO Addr
182    case args of
183      [arg]  ->
184         case splitFunTys arg of
185            (arg_tys, res_ty) -> 
186                 mapTc (checkForeignArg isFFIExternalTy) arg_tys         `thenTc_`
187                 checkForeignRes True  {-NonIO ok-} isFFIResultTy res_ty `thenTc_`
188                 checkForeignRes False {-Must be IO-} isAddrTy      res
189      _      -> check False (illegalForeignTyErr True{-Arg-} ty)
190  | otherwise =
191      mapTc (checkForeignArg isFFIExternalTy) args               `thenTc_`
192      checkForeignRes True {-NonIO ok-} isFFIResultTy res
193  
194 checkForeignArg :: (Type -> Bool) -> Type -> TcM s ()
195 checkForeignArg pred ty = check (pred ty) (illegalForeignTyErr True{-Arg-} ty)
196
197 -- Check that the type has the form 
198 --    (IO t) or (t) , and that t satisfies the given predicate.
199 --
200 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM s ()
201 checkForeignRes non_io_result_ok pred_res_ty ty =
202  case (splitTyConApp_maybe ty) of
203     Just (io, [res_ty]) 
204         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
205         -> returnTc ()
206     _   
207         -> check (non_io_result_ok && pred_res_ty ty) 
208                  (illegalForeignTyErr False{-Res-} ty)
209 \end{code}
210
211 Warnings
212
213 \begin{code}
214 check :: Bool -> Message -> TcM s ()
215 check True _       = returnTc ()
216 check _    the_err = addErrTc the_err `thenNF_Tc_` returnTc ()
217
218 illegalForeignTyErr isArg ty
219   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
220          4 (hsep [ppr ty])
221   where
222    arg_or_res
223     | isArg     = ptext SLIT("argument")
224     | otherwise = ptext SLIT("result")
225
226 foreignDeclCtxt fo = 
227  hang (ptext SLIT("When checking declaration:"))
228   4   (ppr fo)
229 \end{code}