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